0

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

5
  • 3
    You have exit() in there, so it will only run the loop once. You also only fetch one row in your select query, while you loop the $_POST['order-check'] until the end (except you exit after the first iteration). Commented Jul 11, 2019 at 6:41
  • Your second query doesn't use anything from $row. Why are you doing it in the loop? Commented Jul 11, 2019 at 6:49
  • Don't put the solution in the question. Commented Jul 11, 2019 at 6:50
  • @Barmar should I just use if($result) ? Commented Jul 11, 2019 at 6:52
  • Never mind, I thought you were doing while ($row = mysqli_fetch_assoc($result)). Commented Jul 11, 2019 at 6:54

1 Answer 1

1

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();
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.