JSON 到 PHP,然后是 foreach?
我从 jQueryscript 向 PHP 页面发送一个有效的 JSON 字符串:
var data = '{
"data":[
{
"id":"12",
"checked":"true"
},{
"id":"4",
"checked":"false"
},{
"id":"33",
"checked":"false"
}
]
}';
$.post ("page.php", { data_input:data }, function (data) {
// code
});
在 PHP 页面中获取数据后,我使用 json_decode 方法解析它,然后尝试在 foreach 中使用它为 PDO
查询创建的 语句:
<?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;
?>
这会返回错误:
PHP 警告:为 /home/.../page.php 第 XX 行的 foreach() 提供的参数无效
我可以找到在 foreach
语句中使用 JSON 数据的方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
json_last_error()< 确保 json_decode 运行完毕/code>
$data_input
是一个数组。 json_decode() 操作的结果是不一定总是数组:尽管就你而言,应该是这样。我打赌解码错误。
json_last_error()
$data_input
is an array. The result of a json_decode() operation is not necessarily always an array:though in your case, it should be. I am betting on a decoding error.
您将
$_REQUEST['data']
视为 JSON 字符串,但情况并非总是如此(如果我愿意,我可以发送具有无效值的请求),也不会它始终是表示数组或字典的 JSON 字符串。您需要事先检查,如果没有,请做出相应反应。现在,针对您的实际错误。您写道:
这将是一个错误,因为
page.php
没有被引用。但即使假设它在您的实际代码中,服务器端数据也会存储在$_POST['data_input']
中,而不是$_POST['data']
。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:
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']
.我发现了问题:
I found the problem: