Reputation: 19476
I send a valid JSON string to my PHP page from jQueryscript:
var data = '{
"data":[
{
"id":"12",
"checked":"true"
},{
"id":"4",
"checked":"false"
},{
"id":"33",
"checked":"false"
}
]
}';
$.post ("page.php", { data_input:data }, function (data) {
// code
});
Once I get the data in my PHP page, I parse it with the json_decode
method, and then try to use it in a foreach
statement created for a PDO
query:
<?php
$data_input = json_decode ($_REQUEST['data_input'], true);
$sql = "UPDATE my_table SET user_enabled = :checked WHERE node_prop_id = :id";
$stmt = $dns->prepare ($sql);
foreach ($data_input as $data) {
$ok = $stmt->execute ($data);
$num = $stmt->rowCount ();
}
if ($ok) return 1;
else return 0;
?>
This returns me the error:
PHP Warning: Invalid argument supplied for foreach() in /home/.../page.php on line XX
Can I find a way to use my JSON data in the foreach
statement?
Upvotes: 1
Views: 1669
Reputation: 19476
I found the problem:
<?php
// I've changed $data to $json for more clarity
$json = json_decode (stripslashes ($_REQUEST['json_string']), true); // added stripslashes method for more debug, but i think it still works without
$json = $json["data"]; // this was the problem
$sql = "UPDATE my_table SET user_enabled = :checked WHERE node_prop_id = :id";
$stmt = $dns->prepare ($sql);
foreach ($json as $value) {
$ok = $stmt->execute ($value);
$num = $stmt->rowCount ();
}
if ($ok) return 1;
else return 0;
?>
Upvotes: 1
Reputation: 24577
You're treating $_REQUEST['data']
as if it were a JSON string, which is not always the case (I could send a request with an invalid value if I wanted to), nor will it always be a JSON string representing an array or dictionary. You would need to check beforehand, and react accordingly if it isn't.
Now, for your actual bug. You wrote:
$.post (page.php, { data_input:data }, function (data) {
// code
});
This would be an error, since page.php
is not quoted. But even assuming that it is in your actual code, server-side the data would be stored in $_POST['data_input']
, not $_POST['data']
.
Upvotes: 1
Reputation: 449465
json_last_error()
$data_input
is an array. The result of a json_decode() operation is not necessarily always an array:Return value
Returns the value encoded in json in appropriate PHP type. Values true, false and null (case-insensitive) are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
though in your case, it should be. I am betting on a decoding error.
Edit: Victor Nicollet spotted the actual error. It's still good to use json_last_error and do some more checks!
Upvotes: 1