我有一个 foreach MySQL 查询,我希望返回具有相同订单 ID 的所有结果,但它会生成相同的产品 ID。它知 Prop 有该特定订单 ID 的正确条目数量,因为计数器在运行完具有相同订单 ID 的所有条目后停止。
我的 foreach 语句:
$i = 0;
foreach ($_SESSION["cart_array"] as $per_item)
{
$item_id = $per_item['latestid'];
$fetchorder = mysql_query("SELECT ISBN FROM transactions WHERE Order_ID='$latestid'");
while ($row = mysql_fetch_array($fetchorder))
{
$ISBN = $row["ISBN"];
};
echo "ISBNs in order $latestid are: $ISBN";
echo "<br>";
$i++;
};
$latestid 是从之前的查询中获取的,这会正确地收集最新的订单 ID。
我的数据库表如下所示:
Table: transactions
Order_ID | ISBN
25 | 11111111
25 | 22222222
25 | 33333333
然而,我得到的结果是:
latestid = 25
ISBNs in order 25 are: 33333333
ISBNs in order 25 are: 33333333
ISBNs in order 25 are: 33333333
(latestid = 25 是从之前的 sql 查询中回显的,仅用于测试目的以确保其正常工作。)
当它应该列出该特定订单 ID 中的所有商品时,是什么导致它显示相同的商品 ID (ISBN)?
提前致谢,
杰米。
最佳答案
您的 echo 不在循环内,因此它仅打印对 $ISBN 的最后分配。将其放在 while 循环内。你的代码应该是这样的。
i = 0;
foreach ($_SESSION["cart_array"] as $per_item)
{
$item_id = $per_item['latestid'];
$fetchorder = mysql_query("SELECT ISBN FROM transactions WHERE Order_ID='$latestid'");
while ($row = mysql_fetch_array($fetchorder))
{
$ISBN = $row["ISBN"];
echo "ISBNs in order $latestid are: $ISBN";
echo "<br>";
};
$i++;
}
关于PHP 5.6 MySQL foreach 查询返回相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44016473/