在IF语句中更新数据库

时间:2017-09-07 20:40:13

标签: php mysql sql if-statement sql-update

我正在尝试在IF语句中更新我的数据库,但它似乎没有工作。 email_sent不会改为1.我的陈述是否正确?

$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' ");
}

3 个答案:

答案 0 :(得分:1)

你暂时关闭你的循环太快了。您只是获取循环的最后一个值:

$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' ");
   }
}

答案 1 :(得分:0)

检查$quantity变量,似乎没有正确定义。你的意思是SELECT *吗?

您可能不需要while循环,因为您只处理表的一行,即具有给定id的行。否则,如果您有更多行,则给定的while循环将过早关闭。

$con可能会选择太多列,这可能是不利的。此外,不推荐使用msyql_query,您需要使用mysqli_query或PDO。因此,假设$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' "); } 是您的数据库连接:

,以下内容可能会有所帮助
_includes

答案 2 :(得分:0)

分辨率是与查询相关的时间,因此我需要关闭连接并在HTML之后打开一个新连接来查询数据库。

非常感谢所有人的评论,因为它们都非常有用,将来会帮助我。

:)