-1

I have some data in JSON format in a text file as below. I need to insert this data into mysql using php but can't do it.

{"address":"+92 334 6629424","service_center":"Test Sending Sms","id":3,"locked":0,"person":0,"protocol":0,"read":0,"reply_path_present":2,"seen":0,"error_code":0,"status":1,"date":1873326412,"thread_id":1,"type":-1}

My PHP file has the code like this.

<?php $source_file  = "SMS2012-05-21.txt"; $handle = fopen("SMS2012-05-21.txt", "r");
$col_names = implode(",", fgetcsv($handle)); // Getting comma separated list of col name

 $link = mysql_connect('localhost', 'root', '');
 mysql_select_db("messages");
 while (($data = fgetcsv($handle)) !== FALSE) {
 $values = "";
 foreach($data as $key => $value) {
     if ($key != 0) $values .= ", ";
     $values .= "'".mysql_escape_string($value)."'";
 }
 mysql_query('INSERT INTO messages ('.$col_names.') VALUES ('.$values.')');
 }
 ?>

I can't find any result nor any error. Could any one please help me in this regard that where i am wrong?

4

2 に答える 2

1

jsonデータを操作するには、 json_decode関数を使用する必要があります。

<?php


  $source_file  = "SMS2012-05-21.txt";
  $string = file_get_contents($source_file);
  $json = json_decode($string,true);

  //DB Conn Handling Stuff

  $cols = array(); $values = array();

  foreach($json as $key=>$value)
  {
      array_push($cols,'`' . $key . '`');
      if(is_string($value))
      {
         array_push($values,'\''.$value.'\'');
      }
      else
      {
         array_push ($values, $value);
      }
  }

  $col_name = implode(',',$cols);
  $col_value = implode(',',$values);

  $query = 'INSERT INTO messages('.$col_name.') VALUES ('.$col_value.')';
  mysql_query($query,$connection) or die(echo mysql_error());      

?>
于 2012-05-24T15:03:43.497 に答える
0

多分私は何かを逃したので、あなたはそれをこのように使うべきです:

<?php $source_file  = "SMS2012-05-21.txt"; 
$handle = fopen("SMS2012-05-21.txt", "r");
$data = fread($handle, filesize($source_file));
$jsonArray = json_decode($data, true);

$keys = implode(',', array_keys($jsonArray));
$values = "'" . implode("','", $jsonArray) . "'";

$link = mysql_connect('localhost', 'root', '');
mysql_select_db("messages");

mysql_query('INSERT INTO messages ('.$keys.') VALUES ('.$values.')');
于 2012-05-24T14:25:42.507 に答える