Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

UsmanBasharmal's avatar

foreach array wise multi SQL query not working in PHP

I am trying to execute multiple queries with the multiple selected checkbox value-wise in PHP. I am facing trouble that my code is executing only one checkbox value-wise query and the rest is denied.

I checked on StackOverflow about this issue and I got lots of threads about foreach loop but in my case, it is not working when I am applying that.

Please help me, I am first time trying the foreach loop and so that I have a bit confusing about the same. How I fix this? it only works for the first check value but I want all checked checkboxes. I am trying to fetch data from the database of those particular ids which value I selected in the checkbox. and echo it in the array for that all query as I mention below-

Sending Form Data format as seen in dev tool

referenceID[]: PO0203211
referenceID[]: PO203213

PHP

$checkbox = $_POST['referenceID'];
foreach ($checkbox as $chk) {
    $stmt = $con->prepare(
        "SELECT  * FROM `table` WHERE `ref` = :referenceid"
    );
    $stmt->execute([':referenceid' => $chk]);
    $stmt = $stmt->fetchAll();

    $response = [];
    $i = 1;
    foreach ($stmt as $data) {
        $response[] = [
            "slno" => $i,
            "name" => $data['name'],
            "orderid" => $data['address'],
        ];
        $i++;
    }
    echo json_encode($response);
    exit();
}
0 likes
1 reply
UsmanBasharmal's avatar
UsmanBasharmal
OP
Best Answer
Level 3

I solved it My bad, that was becasue of using exit() inside the foreach the code does not continue and only performs the first element,

$checkbox = $_POST['referenceID'];

$response = []; //All Result

foreach ($checkbox as $chk) {
  $stmt = $con->prepare(
      "SELECT  * FROM `table` WHERE `ref` = :referenceid"
  );
  $stmt->execute([':referenceid' => $chk]);
  $stmt = $stmt->fetchAll();


  $i = 1;
  foreach ($stmt as $data) {
      $response[] = [
          "slno" => $i,
          "name" => $data['name'],
          "orderid" => $data['address'],
      ];
      $i++;
  }

}

echo json_encode($response);

Please or to participate in this conversation.