使用 PHP / MySQLi 遍历 json_decoded 数组不适用于更新查询
Using PHP / MySQLi to loop through json_decoded array not working for Update query
我正在使用 json_decode() 解码 Ajax 结果,其中 returns 下面的数组(缩短的示例)。
现在我想遍历这个区域并根据数组中的值更新每个 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();
在您的 foreach
中,键是指数组的索引,而不是您认为的键是什么。您案例中的键实际上是 0、1、2,[...]。
你return一个数组的数组,所以得到你想要的部分如下:
foreach($json as $key => $value) {
$stmt->bind_param('ss', $value['rId'], $value['vId']);
$stmt->execute();
}
我正在使用 json_decode() 解码 Ajax 结果,其中 returns 下面的数组(缩短的示例)。 现在我想遍历这个区域并根据数组中的值更新每个 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();
在您的 foreach
中,键是指数组的索引,而不是您认为的键是什么。您案例中的键实际上是 0、1、2,[...]。
你return一个数组的数组,所以得到你想要的部分如下:
foreach($json as $key => $value) {
$stmt->bind_param('ss', $value['rId'], $value['vId']);
$stmt->execute();
}