如何将文本文件中的数据插入mysql?

时间:2012-05-24 13:52:01

标签: php json

我在文本文件中有一些JSON格式的数据,如下所示。我需要使用php将这些数据插入到mysql中但不能这样做。

{"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}

我的PHP文件包含这样的代码。

<?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.')');
 }
 ?>

我找不到任何结果也没有任何错误。在这方面,有任何人可以帮助我,我错了吗?

2 个答案:

答案 0 :(得分:1)

您应该使用json_decode函数来操作json数据。

<?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());      

?>

答案 1 :(得分: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.')');