JordanPattinson
JordanPattinson

Reputation: 61

Need to execute a sql query with variables from a foreach loop

So I need to run my sql query in a foreach loop, but, say there are two variables in the foreach loop, the query only executes the iteration with the first variable twice, instead of executing both the first and the second variable.

My code

$sql = "SELECT * FROM users WHERE idUsers = '$selected';";

$result = mysqli_query($conn, $sql);
if($row = mysqli_fetch_assoc($result))
{
    foreach($_POST['order-check'] as $check) 
    {
        $sql2 = "UPDATE order_table SET order_status = 'Processing', assigned_vendor = '$selectedvendor' WHERE order_id = '$check';";
        $result2 = mysqli_query($conn, $sql2);
        exit();
    }
}
else{
    echo "failed";
    exit();
}

Here, $selected is a POST variable from another page

Upvotes: 0

Views: 1216

Answers (1)

Stevo S
Stevo S

Reputation: 13

As Qirel mentioned, remove the "exit()" from your foreach statement. Also, please ensure you sanitize any POST or GET variables before inserting into the database :)

Your statement should look like this if you want to loop through all $_POST variables

  foreach($_POST['order-check'] as $check) 
        {
            $sql2 = "UPDATE order_table SET order_status = 'Processing', assigned_vendor = '$selectedvendor' WHERE order_id = '$check';";
            $result2 = mysqli_query($conn, $sql2);
            //exit();
        }

Upvotes: 1

Related Questions