php - JSON 到 PHP,然后是 foreach?

标签 php jquery mysql json pdo

我从 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 Warning: Invalid argument supplied for foreach() in /home/.../page.php on line XX

我能找到一种方法在 foreach 语句中使用我的 JSON 数据吗?

最佳答案

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.

虽然在你的情况下,它应该是。我打赌解码错误。

Edit: Victor Nicollet spotted the actual error. It's still good to use json_last_error and do some more checks!

关于php - JSON 到 PHP,然后是 foreach?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2073408/

相关文章:

javascript - 深入了解如何将两个表单字段提交到 2 页之外的单独页面

php - 多张图片上传到Mysql数据库

php - Jquery .load() 不返回 HTML(URL 中有 ""空格!)

javascript - 如果前一个为空则隐藏下一个元素

java - 在不同用户上创建地理围栏

mysql - 没有关联表如何关联两个表?

php - 当用户在选择字段中选择新选项时,如何运行 mysql 查询?

javascript - 防止空白输入不起作用

javascript - 恢复选中复选框的所有值并将它们插入数组中

mysql - 在记录付款交易时,我应该使用表的 ID 还是直接使用值