PHP-Foreach While循环-输入的每种股票(数量)的电子邮件客户端和更新数据库

我已经在这个问题上停留了一段时间,似乎无法弄清楚。

我正在以整数形式运行数量,例如5。

我想遍历每个数量,直到达到最大数量为止,最大是他们从0开始输入的数量。

这是我要查询的股票项目:

$product_id = '1';
$quantity = '2';

$smtp_main = $pdo->prepare('SELECT * FROM `productitems` WHERE `avaliable` = :avaliable AND `assignedProduct` = :assignedProduct LIMIT :limit');
$smtp_main->execute(array(':avaliable' => '0',':assignedProduct' => $product_id,':limit' => $quantity));

$query = $smtp_main->fetchAll();

这是我当前的while循环/ foreach循环:

        // Foreach loop here
        $i = 0;
        $maxiterations = $quantity;

        while($i <= $maxiterations) {
            foreach($query as $row_product) {
                $product_link_stock = $row_product['code'];
                $stock_id_stock = $row_product['id'];
            }

            $message .= "<tr style='background: #eee;'><td><strong>Email/username:Pass(".$i."):</strong> </td><td>".$product_link_stock."</td></tr>";
            $i++;

            // Update stock foreach stock product they require (quantity depends on this)
            $updateStock = $pdo->prepare('UPDATE `productitems` SET `avaliable` = :avaliable WHERE `id` = :id');
            $updateStock->execute(array(':avaliable' => '1',':id' => $stock_id_stock));
        }

然后我的邮件功能不在两个循环中,并且它可以毫无问题地发送邮件。

我得到的错误是库存只下降了1,并且在收到的电子邮件中没有显示2支股票-

PHP-Foreach While循环-输入的每种股票(数量)的电子邮件客户端和更新数据库

ccf62904603 回答:PHP-Foreach While循环-输入的每种股票(数量)的电子邮件客户端和更新数据库

如果我理解正确,则$ row_product包含多个产品,并且您仅更新最后一个产品,因为$ message,$ i和$ updateStock不在foreach循环中。 尝试将代码放入foreach循环中。

但是我建议避免嵌套循环,而只使用一个foreach。因为,您多次将可用库存更新为1,所以没有意义。

要生成$ message,可以使用str_repeat()函数

  

更新

foreach($query as $i => $row_product) {
   $product_link_stock = $row_product['code'];
   $stock_id_stock = $row_product['id'];
   $message .= "<tr style='background: #eee;'><td><strong>Email/Username:Pass(".$i."):</strong> </td><td>".$product_link_stock."</td></tr>";

   $updateStock = $pdo->prepare('UPDATE `productitems` SET `avaliable` = :avaliable WHERE `id` = :id');
   $updateStock->execute(array(':avaliable' => '1',':id' => $stock_id_stock));        

}
本文链接:https://www.f2er.com/3131688.html

大家都在问