我正在解码JSON数组,然后在将数据插入mysql之后使用foreach循环...但总是得到"无法保存数据" !
请参阅下面的php脚本,了解我已尝试过的内容:
<?php
$objConnect = mysql_connect("localhost","","");
$objDB = mysql_select_db("test");
$raw_json = <<<EOT
{"data":[
{"PersonName":"first user","PersonEmail":"first@user.tld"},
{"PersonName":"second user","PersonEmail":"second@user.tld"}
]}
EOT;
// $raw_json = $_POST["allData"]; -- passing parameter
$json = json_decode($raw_json);
// echo json_encode($json); --- getting
foreach($json->data as $item){
// echo json_encode($item); --- getting
$strPersonName = $item->PersonName;
// echo json_encode($strPersonName); --- getting
$strPersonEmail = $item->PersonEmail;
// echo json_encode($strPersonEmail); --- getting
/*** Insert ***/
$strSQL = "insert into person (PersonName,PersonEmail)
values (
'".$strPersonName."',
'".$strPersonEmail."',
)
";
$objQuery = mysql_query($strSQL);
if(!$objQuery)
{
$arr['StatusID'] = "0";
$arr['Message'] = "Cannot save data";
}
else
{
$arr['StatusID'] = "1";
$arr['Message'] = "Data stored successfully";
}
}
mysql_close($objConnect);
echo json_encode($arr);
?>
当我使用下面的PHP脚本时,我能够将数据存储到服务器,请检查:
<?php
$objConnect = mysql_connect("localhost","","");
$objDB = mysql_select_db("test");
$_POST["sPersonName"] = "demo";
$_POST["sPersonEmail"] = "deom@demo.tld";
$strPersonName = $_POST["sPersonName"];
$strPersonEmail = $_POST["sPersonEmail"];
/*** Insert ***/
$strSQL = "INSERT INTO person (PersonName, PersonEmail)
VALUES (
'".$strPersonName."',
'".$strPersonEmail."'
)
";
$objQuery = mysql_query($strSQL);
if(!$objQuery)
{
$arr['StatusID'] = "0";
$arr['Message'] = "Cannot save data!";
}
else
{
$arr['StatusID'] = "1";
$arr['Message'] = "Data stored successfully";
}
/**
$arr['StatusID'] // (0=Failed , 1=Complete)
$arr['Error'] // Error Message
*/
mysql_close($objConnect);
echo json_encode($arr);
?>
那么可能是什么原因?为什么我无法将数据存储到mysql表,当我解码json数组?
答案 0 :(得分:1)
您在最后一个值后面有逗号...
更改
$strSQL = "insert into person (PersonName,PersonEmail)
values (
'".$strPersonName."',
'".$strPersonEmail."',
)
";
到
$strSQL = "insert into person (PersonName,PersonEmail)
values (
'".$strPersonName."',
'".$strPersonEmail."'
)
";