0

what is wrong here:

$count = count($_POST['ids']);

for ($x=0; $x<=$count; $x++) {
    $sql = "update home set status = :astatus where id = :aid";
    $st = $db->prepare($sql);
    $st->execute(array(
        ":astatus" => $_POST['stats'][$x],
        ":aid" => $_POST['ids'][$x]
    ));
}

Error: Undefined offset 40...

As I can see in database - the code is executed.

checking:

echo $count; // 40  

echo count($_POST['stats']);  //40

Why I'm getting this error?

1 Answers1

3

You need to use the following for:

for ($x = 0; $x < $count; $x++) { //without =
    //...
}

The 39th element on your $_POST['ids'] array is the 40th element since arrays starting at 0:

$arr = $_POST['ids'];
$arr[0]  // 1st
$arr[1]  // 2nd
// ...
$arr[38] // 39th
$arr[39] // 40th

The code can look like the following:

$arr_ids = $_POST['ids'];
$arr_stats = $_POST['stats'];
$count = count($arr_ids);

if ($count !== count($arr_stats)) {
    //TODO - what is happening if the count of stats and ids are different?
}

$st = $db->prepare("UPDATE home SET status = :astatus WHERE id = :aid");

for ($x = 0; $x < $count; $x++) {
    $st->execute(array(
        ":astatus" => $arr_stats[$x],
        ":aid" => $arr_ids[$x]
    ));
}
Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87