Question: I am trying to update my database inside an IF statement but it doesn't seem to be working. email\_sent doesn't change to 1. Is my statement correct?

```
$result2 = mysql_query ("SELECT * FROM stock_control WHERE id = '$id' ");

while ($row1 = mysql_fetch_array($result2))
{
$item=$row1['item'];
$location=$row1['location'];
$quantity=$row1['quantity'];
$threshold=$row1['threshold'];
$emailSent=$row1['email_sent'];
}

if ($quantity <= $threshold && $emailSent == 0) {
mysql_query("UPDATE stock_control SET quantity=quantity - '$n_quantity', 
email_sent = '1' WHERE id = '$id' ");
} else {
mysql_query("UPDATE stock_control SET quantity=quantity - '$n_quantity' WHERE 
id = '$id' ");
}

```

Answer: 
You are closing your loop too fast for the while. You are just getting the last value of the loop:

```
$result2 = mysql_query ("SELECT * FROM stock_control WHERE id = '$id' ");

while ($row1 = mysql_fetch_array($result2))
{
   $item=$row1['item'];
   $location=$row1['location'];
   $quantity=$row1['quantity'];
   $threshold=$row1['threshold'];
   $emailSent=$row1['email_sent'];

   if ($quantity <= $threshold && $emailSent == 0) {
      mysql_query("UPDATE stock_control SET quantity=quantity - '$n_quantity', 
      email_sent = '1' WHERE id = '$id' ");
   } else {
      mysql_query("UPDATE stock_control SET quantity=quantity - '$n_quantity' WHERE 
      id = '$id' ");
   }
}

```
Check on the`$n_quantity` variable, it does not seem to be properly defined. Did you mean `$quantity` instead?

You may not need the while loop, since you are dealing with only one row of the table, the row with the given id. Otherwise, if you had more rows, the while loop as given would have been prematurely closed. 

`SELECT *` could select too many columns, which might be disadvantageous. Also, the use of msyql\_query is deprecated, you will need to use mysqli\_query or PDO. So the following might be helpful, assuming that `$con` is your database connection:

```
$result2 = mysqli_query($con,"SELECT item, location, quantity, threshold, email_sent from stock_control where id = '$id'");

list($item,$location,$quantity,$threshold,$emailSent) = mysqli_fetch_array($result2);

if ($quantity <= $threshold && $emailSent == 0) {
      mysqli_query($con,"UPDATE stock_control SET quantity=quantity - '$quantity', 
      email_sent = '1' WHERE id = '$id' ");
   } else {
      mysqli_query($con,"UPDATE stock_control SET quantity=quantity - '$quantity' WHERE id = '$id' ");
   }

```