Json反序列化对象列表并保存到DB

时间:2017-04-07 07:40:38

标签: php json

我试图将这种格式的Json插入数据库。

 {  
     "firstName": "Brett"
 }

此格式正确插入。

但如果我改变下面的格式:

 [  
 {  
  "firstName": "Brett"
 },
 {
 "firstName": "John"
 }
]

对于以下脚本,我只能插入第一条记录。

<?php

 $data = json_decode(file_get_contents('php://input'), true);
 /*Server credentials*/
 $arraykey=array_keys($data); 
 $array=$data[$arraykey[0]]; 
 try 
 {
   //SQL Server execute
  foreach($data as $array)
  {
      $count = $dbh->exec("INSERT INTO table(firstname) VALUES ('" . implode("', '", $array) . "')" ) or die(print_r($dbh->errorInfo(), true)); 
    echo count($data);                                                                                                                      
    $dbh = null;
    echo 'Data Successfully inserted!!<br />';
   }
 }
catch(PDOException $e)
{
  echo $e->getMessage();
 }

如何插入上述脚本的所有json记录。

0 个答案:

没有答案