【问题标题】:Updating database in an IF Statement在 IF 语句中更新数据库
【发布时间】:2017-09-07 20:40:13
【问题描述】:

我正在尝试在 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' ");
}

【问题讨论】:

  • email_sent 是整数还是字符串?因为'1' 是一个字符串。你应该只使用1
  • @JuanCarlosOropeza 这不是问题,MySQL 在这种情况下会自动转换类型
  • 也许您应该展示整个脚本以便更好地理解。例如,$n_quantity 变量来自哪里?

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


【解决方案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' ");
   }
}

【讨论】:

  • 所以它更新数据库但没有足够的时间来执行下一个 IF,如果这有意义的话。我有它准备和电子邮件,然后这个代码 if ($emailSent == 1) { $message = implode("\r\n", $message); mysql_query("更新 stock_control SET email_sent = 2 WHERE id = '$id'");; }
  • 不,抱歉我解释错了,不是时间问题。您必须在 while 循环内更新数据库。尽管 ..{ ... }。我只是移动了 while 的结束以包含循环。
【解决方案2】:

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

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

SELECT * 可以选择太多列,这可能是不利的。此外,不推荐使用 msyql_query,您将需要使用 mysqli_query 或 PDO。因此,假设$con 是您的数据库连接,以下内容可能会有所帮助:

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

【讨论】:

    【解决方案3】:

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

    非常感谢大家的 cmets,因为它们都非常有用,将来会帮助我。

    :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-21
      • 2015-05-09
      • 1970-01-01
      • 2011-01-28
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多