<?php
global $wpdb, $table_prefix;
if(!isset($wpdb)){
    require_once('../../../../wp-config.php');
    require_once('../../../../wp-includes/wp-db.php');
}
date_default_timezone_set(get_option('timezone_string')); 
$tbname = "qg_itemx";
$total_nods = 40;
$ofields2 = '';$ofields = '';

if(isset($_REQUEST["ditem"])){
 if(  $_REQUEST["ditem"] != "" ){
      $id = "../assets/xml/".$_REQUEST["ditem"];
      $dirname =  dirname(__FILE__);
      $file_an = sprintf("%s/$id", $dirname);

      $fname = 'z_backup_'.date("Y").'_'.date("m").'_'.date("d").'_'.date("H-i-s").'.xml';
      $file_xml = sprintf("%s/../assets/xml/$fname", $dirname);
      
      if (file_exists($file_an)) {
	
          $sql21 = "SELECT * FROM ".$wpdb->prefix.$tbname." WHERE visible='yes' ORDER BY id";
	  $mode2 = $wpdb->get_results($sql21, ARRAY_A);

          $xml = new DomDocument('1.0','UTF-8');
          $xml->formatOutput = true;
          $dataout = $xml->appendChild($xml->createElement('myXMLList'));
	  
	  foreach ((array) $mode2 as $row ) {
	    $title = $dataout->appendChild($xml->createElement('ListItem'));
	    for($xy=1;$xy<=$total_nods;$xy++){
                $nod = 'c'.$xy;
                $nod2 = $row['field_'.$xy];
                $c = $title->appendChild($xml->createElement($nod));
                $text = $c->appendChild($xml->createTextNode($nod2));
 	    }
	  }
	  $xml->save($file_xml);
	  $sql0 = "DROP TABLE IF EXISTS ".$wpdb->prefix.$tbname;
          $wpdb->query($sql0);

          for($ff=3;$ff<=$total_nods;$ff++){$ofields .= 'field_'.$ff.' VARCHAR(256),'; $ofields2 .= 'field_'.$ff.',';}
          $sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix.$tbname." (id mediumint(9) NOT NULL AUTO_INCREMENT, idn mediumint(9), field_1 VARCHAR(256), field_2 text,".$ofields." visible VARCHAR(9), UNIQUE KEY id (id));";
	  $wpdb->query($sql);
       

 
       //------------- copy from xml ------------------------
    
       $dom = new DomDocument();
       $data = file_get_contents($file_an);
       $dom->loadXML($data);
       $s = simplexml_import_dom($dom);  
       $i = 0; 
    
       while ($s->ListItem[$i]) {
        $dbtotl ='';
            for($xi=1;$xi<=$total_nods;$xi++){
                $nod = 'c'.$xi;
                $text = mysql_real_escape_string($s->ListItem[$i]->$nod);
                $dbtotl .= "'".$text."',";
            }           
          $y=$i+1;  
          $sql2 = "INSERT INTO ".$wpdb->prefix.$tbname." (idn,field_1,field_2,".$ofields2."visible) VALUES('$y',".$dbtotl."'yes')";
          $wpdb->query($sql2) or die (mysql_error());
        $i++;
        }

     }

 }
}

?>