Using PHP / MySQLi to loop through json_decoded array not working for Update query

I am using json_decode() to decode an Ajax result which returns the below array (shortened example). Now I want to loop through this area and to update the rId for each vId as per the values from the array but this part does not work.
Can someone show me how to do the loop part correctly here (the query itself should be ok) ?
My array:
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"
}
}
My 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();
Answer
Solution:
In yourforeach
, the key refers to the index of the array rather than what you consider the key to be. The keys in your case are actually 0, 1, 2, [...].
You return an array of arrays, so get the parts you want as follows:
foreach($json as $key => $value) {
$stmt->bind_param('ss', $value['rId'], $value['vId']);
$stmt->execute();
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: invalid argument supplied for foreach() laravel
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.