I am decoding JSON array and then using foreach to loop through after that inserting data to mysql... but always getting "Cannot save data" !
see below php script to know what i have tried yet:
$objConnect = mysql_connect("localhost","","");
$objDB = mysql_select_db("test");
$raw_json = << {"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);
?>
and when i use below php script, i am able to store data to server, check this:
$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);
?>
So what could be the reason? why i am not able to store data to mysql table, when i am decoding json array ?
Answer
You have a comma after the last value...
Change
$strSQL = "insert into person (PersonName,PersonEmail)
values (
'".$strPersonName."',
'".$strPersonEmail."',
)
";
into
$strSQL = "insert into person (PersonName,PersonEmail)
values (
'".$strPersonName."',
'".$strPersonEmail."'
)
";
No comments:
Post a Comment