我有一个名为 cart
的表,我想通过 PHP 返回其中的所有行。
所以我编写了这个:
$get_add = "SELECT * FROM cart WHERE ip_add = '1'";
$run_add = mysqli_query($con,$get_add);
$cart_items = [];
while($row_results = mysqli_fetch_array($run_add))
{
$item = array(
'table_id' => $row_results['table_id'],
'pro_id' => $row_results['product_id'],
'pro_title' => $row_results['product_title'],
'pro_price' => number_format($row_results['product_price'], '0', '', ','),
'pro_supplier' => $row_results['product_supplier'],
'pro_img' => $row_results['product_image'],
);
$cart_items[] = $item;
foreach($cart_items as $cart){
echo $cart['pro_title']
}
}
所以这工作正常,但唯一的问题是它只显示一个结果。但是,有几行将相同的 ip_add
设置为 1
。
所以我恳求你让我知道我的错是什么以及显示所有表格行的正确方法是什么?
提前致谢!
最佳答案
将内部 foreach
循环移到 while
之外,如下所示:
while($row_results = mysqli_fetch_array($run_add))
{
$item = array(
'table_id' => $row_results['table_id'],
'pro_id' => $row_results['product_id'],
'pro_title' => $row_results['product_title'],
'pro_price' => number_format($row_results['product_price'], '0', '', ','),
'pro_supplier' => $row_results['product_supplier'],
'pro_img' => $row_results['product_image'],
);
$cart_items[] = $item;
}
foreach($cart_items as $cart){
echo $cart['pro_title'];
}
基本上,您所做的将始终返回数组 $cart_itmes
的最后一项,因为它位于 while
循环内部。因此,将其更改为我在上面代码片段中所做的方式。
关于PHP 不显示表中的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48943514/