【问题标题】:insert loop only inserts one row not all row插入循环只插入一行而不是所有行
【发布时间】:2020-03-07 09:59:58
【问题描述】:
<?php
    require 'database.php';

    $msg= "Quntity is less than 10";


    $numResults = mysqli_query($conn, "select  COUNT(*) as `count` from item  where item_quantity <10");
    $row = mysqli_fetch_array($numResults);
    $count = $row['count'];
    if ($count>0) {



        $query = mysqli_query($conn, "select item_name from item  where item_quantity <10");

        while ($notify = mysqli_fetch_assoc($query)) {




            $td2 = $notify['item_name'];
 $query = mysqli_query($conn, "insert  into notification (notification_name ,msg , status , notification_date)
VALUES('$td2','$msg','unread' , current_time )");

        }


    }
?>

这里的问题是每次刷新页面时执行的代码,插入循环只插入一行而不是所有行。

【问题讨论】:

  • 在你的循环中你重新使用$query变量,它也是SELECT。您的代码可以对使用准备好的语句进行一些更改,删除不必要的第一个 SELECT 并将 INSERT 转换为 INSERT...SELECT... (对不起,我刚刚离开,但这条评论可能会有所帮助)。

标签: php mysql


【解决方案1】:

无需先从数据库中获取数据,然后再将其写回。你可以在这里发出INSERT ... SELECT ...

INSERT INTO notification
            (notification_name,
             msg,
             status,
             notification_date)
            SELECT item_name,
                   'Quntity is less than 10',
                   'unread',
                   current_time
                   FROM item
                   WHERE item_quantity < 10;

为了始终获得准确的数字,您可以创建一个视图,在必要时计算消息。

CREATE VIEW notification
AS
SELECT item_name,
       'Quntity is less than 10',
       'unread',
       current_time
       FROM item
       WHERE item_quantity < 10;

【讨论】:

  • 插入效果很好,但是当我刷新页面时再次插入我想在刷新页面时检查它们是否是新的 item_quantity
猜你喜欢
  • 2013-07-27
  • 1970-01-01
  • 1970-01-01
  • 2018-01-13
  • 2015-05-10
  • 1970-01-01
  • 2014-07-20
  • 2014-04-04
  • 1970-01-01
相关资源
最近更新 更多