0

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(); 
keewee279
  • 1,656
  • 5
  • 28
  • 60
  • Please read: [Should we ever check for mysqli_connect() errors manually?](https://stackoverflow.com/q/58808332/1839439) – Dharman Apr 25 '20 at 23:22

1 Answers1

1

In your foreach, 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();
}
bdbd
  • 91
  • 7