将json_encode值插入mysql表

时间:2014-12-26 05:51:45

标签: php json

我在PHP工作。我有以下值来完成json_encode函数。当我打印变量$ vmndetails时,我得到了以下细节。

[{
   "id":"1",
   "smsid":"4781366",
   "senderid":"289613638",
   "textcontent":"Good day reply",
   "msgdate":"2014-12-17 13:04:20",
   "charsetval":"UTF-8",
   "userid":"",
   "reprtdate":"2014-12-17 11:04:21"
},   
{
   "id":"7",
   "smsid":"4781467",
   "senderid":"289761363",
   "textcontent":"Good",
   "msgdate":"2014-12-17 13:21:18",
   "charsetval":"UTF-8",
   "userid":"",
   "reprtdate":"2014-12-17 11:21:21"
}]

我必须将这些值插入到我的mysql表中。

所以我写下了这个函数。

mysql->query( "INSERT INTO twowaysms(id,smsid,senderid,textcontent,msgdate,charsetval,userid,reprtdate) VALUES "."(" . implode(",",$vmndetails) . ")");

但是我收到的错误是'插入值列表与列列表不匹配:1136列数与第1行的值计数不匹配。我在这里看到了很多相同的问题,但我找不到解决方案。如何解决这个问题?请有人帮帮我..

1 个答案:

答案 0 :(得分:1)

你有多维数组数据,所以试试这个 -

// http://ideone.com/xX2HNU
$vmndetails = '[{"id":"1","smsid":"4781366","senderid":"289613638","textcontent":"Good day reply","msgdate":"2014-12-17 13:04:20","charsetval":"UTF-8","userid":"","reprtdate":"2014-12-17 11:04:21"},{"id":"7","smsid":"4781467","senderid":"289761363","textcontent":"Good","msgdate":"2014-12-17 13:21:18","charsetval":"UTF-8","userid":"","reprtdate":"2014-12-17 11:21:21"}]';

$vmndetails = json_decode($vmndetails, true);
$values = "";
foreach($vmndetails as $v) {
    $values .= "(".implode(", ", $v)."), "
}
$values = rtrim($values, ", ");

mysql->query( "INSERT INTO 
    wowaysms(id,smsid,senderid,textcontent,msgdate,charsetval,userid,reprtdate) 
    VALUES {$values} ");