Insert XML Data into Mysql Table Using PHP with Ajax

时间:2018-02-03 08:28:03

标签: php mysql ajax xml

I am using the below PHP file to upload XML to MySQL database, but the issue is my table name is Con-1 and cannot use it. I have error in the below line:

array(
     ':name'   => $data->Con-1[$i]->name,
     ':address'  => $data->Con-1[$i]->address,
     ':gender'  => $data->Con-1[$i]->gender,
     ':designation' => $data->Con-1[$i]->designation,
     ':age'   => $data->Con-1[$i]->age
    )

please help me to solve it

    <?php
//import.php
sleep(3);
$output = '';
if(isset($_FILES['file']['name']) &&  $_FILES['file']['name'] != '')
{
 $valid_extension = array('xml');
 $file_data = explode('.', $_FILES['file']['name']);
 $file_extension = end($file_data);
 if(in_array($file_extension, $valid_extension))
 {
  $data = simplexml_load_file($_FILES['file']['tmp_name']);
  $connect = new PDO('mysql:host=localhost;dbname=testing','root', '');
  $query = "
  INSERT INTO `Con-1`
   (name, address, gender, designation, age) 
   VALUES(:name, :address, :gender, :designation, :age);
  ";
  $statement = $connect->prepare($query);
  for($i = 0; $i < count($data); $i++)
  {
   $statement->execute(
    array(
     ':name'   => $data->Con-1[$i]->name,
     ':address'  => $data->Con-1[$i]->address,
     ':gender'  => $data->Con-1[$i]->gender,
     ':designation' => $data->Con-1[$i]->designation,
     ':age'   => $data->Con-1[$i]->age
    )
   );

  }
  $result = $statement->fetchAll();
  if(isset($result))
  {
   $output = '<div class="alert alert-success">Import Data Done</div>';
  }
 }
 else
 {
  $output = '<div class="alert alert-warning">Invalid File</div>';
 }
}
else
{
 $output = '<div class="alert alert-warning">Please Select XML File</div>';
}

echo $output;

    ?>

1 个答案:

答案 0 :(得分:0)

You should be able to do it using variable variables, so first assign Con-1 to a variable and then substitute this variable for the name in the assignment...

   $var = 'Con-1';
   $statement->execute(
    array(
     ':name'   => $data->$var[$i]->name,
     ':address'  => $data->$var[$i]->address,
     ':gender'  => $data->$var[$i]->gender,
     ':designation' => $data->$var[$i]->designation,
     ':age'   => $data->$var[$i]->age
    )
   );