提问人:keewee279 提问时间:4/26/2020 更新时间:4/26/2020 访问量:59
使用 PHP / MySQLi 遍历不适用于更新查询json_decoded数组
Using PHP / MySQLi to loop through json_decoded array not working for Update query
问:
我正在使用 json_decode() 解码返回以下数组的 Ajax 结果(缩短示例)。 现在我想遍历这个区域,并根据数组中的值更新每个 vId 的 rId,但这部分不起作用。
有人可以告诉我如何在这里正确执行循环部分(查询本身应该没问题)吗?
我的阵列:
array(3) {
[0]=>
array(2) {
["vId"]=>
string(8) "04567901"
["rId"]=>
string(6) "DE-003"
}
[1]=>
array(2) {
["vId"]=>
string(8) "04567902"
["rId"]=>
string(6) "DE-008"
}
[2]=>
array(2) {
["vId"]=>
string(8) "04567903"
["rId"]=>
string(6) "DE-009"
}
}
我的 PHP / MySQLi:
$postData = $_POST;
$transferData = $_POST['transferData'];
$json = json_decode($transferData, true);
$conn = new mysqli($host, $username, $password, $database);
if($conn->connect_error) {
die("Connection Error: " . $conn->connect_error);
}
$stmt = $conn->prepare("UPDATE locations l SET l.rId = ? WHERE l.vId = ?");
foreach($json as $vId => $rId) {
$stmt->bind_param('ss', $rId, $vId);
$stmt->execute();
}
$stmt->close();
$conn->close();
答:
1赞
bdbd
4/26/2020
#1
在 中,键是指数组的索引,而不是您认为的键是什么。您案例中的键实际上是 0、1、2、[...]。
你返回一个数组数组,所以获取你想要的部分,如下所示:foreach
foreach($json as $key => $value) {
$stmt->bind_param('ss', $value['rId'], $value['vId']);
$stmt->execute();
}
评论
0赞
keewee279
4/26/2020
非常感谢你 - 这正是我做错了。效果完美。:)
评论