php while($row = mysql_fetch_assoc($result)) - 如何 foreach $row?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6962771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
while($row = mysql_fetch_assoc($result)) - How to foreach $row?
提问by Craig van Tonder
I am working on a simple order system.
我正在研究一个简单的订单系统。
the peice of code I am stuck on is the following:
我坚持使用的代码如下:
if (isset($_GET['cart']))
{
$cart = array();
$total = 0;
foreach ($_SESSION['cart'] as $id)
{
foreach ($items as $product)
{
if ($product['id'] == $id)
{
$cart[] = $product;
$total += $product['price'];
break;
}
}
}
include 'cart.html.php';
exit();
}
This is the code is build on a preset array. I am working with a table with a few columns in mysql.
这是建立在预设数组上的代码。我正在处理一个在 mysql 中包含几列的表。
I have decided on the following:
我决定了以下几点:
if (isset($_GET['cart']))
{
$cart = array();
$total = 0;
foreach ($_SESSION['cart'] as $id)
{
while($row = mysql_fetch_assoc($productsSql)) {
foreach ($row as $product)
{
if ($product['id'] == $id)
{
$cart[] = $product;
$total += $product['price'];
break;
}
}
}
include 'cart.html.php';
exit();
}}
To display this "cart" I have decided on this:
为了显示这个“购物车”,我决定这样做:
foreach ($cart as $item) {
$pageContent .= '
<tr>
<td>'.$item['desc'].'</td>
<td>
R'.number_format($item['price'], 2).'
</td>
</tr>
';
}
All this seems to do is produce my cart in a fashion where when viewed it displays a list of only the items' id, e.g. where the description and price are supposed to be, I only get the items id in both fields... I also get a total price of 0.
所有这一切似乎都是以一种方式生成我的购物车,当查看它时,它只显示项目 ID 的列表,例如,描述和价格应该在哪里,我只在两个字段中获得项目 ID...我也得到总价为 0。
Can anyone spot where I am going wrong here?
任何人都可以发现我在这里出错的地方吗?
Or atleast try to give me some input so that I get going in the right direction!
或者至少尝试给我一些意见,以便我朝着正确的方向前进!
Thanks!!
谢谢!!
$productsQuery = 'SELECT `id`, `refCode`, `desc`, `pack`, `measure`, `quantity`, `deptCode`, `taxable`, `price1`, `price2`, `crdCode`, `cost1`, `cost2` FROM `products` ORDER BY `desc` ';
$productsSql = mysql_query($productsQuery) or die(mysql_error());
if (mysql_num_rows($productsSql) == 0) {
die('No results.');
} else {
$orderContent = '';
while($row = mysql_fetch_assoc($productsSql)) {
$prId = $row['id'];
$prRefCode = $row['refCode'];
$prDesc = $row['desc'];
$prPack = $row['pack'];
$prMeasure = $row['measure'];
$prQuantity = $row['quantity'];
$prDeptCode = $row['deptCode'];
$prTaxable = $row['taxable'];
$prPrice1 = $row['price1'];
$prPrice2 = $row['price2'];
$prCrdCode = $row['crdCode'];
$prCost1 = $row['cost1'];
$prCost2 = $row['cost2'];
$orderContent .= '
<tr>
<td>'.$prId.'</td>
<td>'.$prDesc.'</td>
<td>'.$prPack.'x'.$prSize.' '.$prMeasure.'</td>
<td>R'.$prPrice1.'</td>
<td>
<form action="" method="post">
<div>
<input type="text" size="3" name="quantity" />
</div>
</form>
</td>
<td>
<form action="" method="post">
<div>
<input type="hidden" name="id" value="'.$prId.'" />
<input type="submit" name="action" value="Order" />
</div>
</form>
</td>
</tr>
';
}}
回答by 65Fbef05
Let's say that each of the rows in your database looks like this...
假设数据库中的每一行看起来像这样......
[product_id][product_name][product_description][product_price]
When you assign your query return to a variable passed through mysql_fetch_assoc()
using a while loop, each pass will isolate a whole row. Of which you can piece apart manually by array key reference ($array['product_id']
) or by using a foreach loop. I think the problem you're having is that you are mixing this up. Keeping the above example table layout in mind, you could do something like the following:
当您将查询返回分配给mysql_fetch_assoc()
使用 while 循环传递的变量时,每次传递都会隔离整行。您可以通过数组键引用 ( $array['product_id']
) 或使用 foreach 循环手动拆分其中的部分。我认为你遇到的问题是你把它搞混了。记住上面的示例表格布局,您可以执行以下操作:
while ($tableRow = mysql_fetch_assoc($query)) { // Loops 3 times if there are 3 returned rows... etc
foreach ($tableRow as $key => $value) { // Loops 4 times because there are 4 columns
echo $value;
echo $tableRow[$key]; // Same output as previous line
}
echo $tableRow['product_id']; // Echos 3 times each row's product_id value
}
Look at this line in your code: if ($product['id'] == $id) { }
查看代码中的这一行: if ($product['id'] == $id) { }
I think you probably mean if ($row['id'] == $id) { }
instead.
我想你的意思可能是if ($row['id'] == $id) { }
相反。
回答by Marc B
Your middle code block makes no sense. You loop over session variables, and run a query each time... but it's the SAME query, and using an undefined variable to boot. Looping over a result row doesn't make much sense, as you'd be looping over the individual fields that your query returns for each row.
您的中间代码块毫无意义。你循环会话变量,每次运行一个查询......但它是相同的查询,并使用未定义的变量来启动。遍历结果行没有多大意义,因为您将遍历查询为每一行返回的各个字段。
e.g. If your products table has just (id, name, description)
as fields, then $row
would be an array that looks like:
例如,如果您的产品表只有(id, name, description)
as 字段,那么$row
将是一个如下所示的数组:
$row = array('id' => xxx, 'name' => yyy, 'description' => zzz);
When you foreach()
on $row()
, you'd not getting individual products, you'd be getting those fields in the row. $product would be xxx
, then yyy
, then zzz
.
当您foreach()
打开 时$row()
,您不会获得单个产品,而是会获得行中的那些字段。$product 将是xxx
, then yyy
, then zzz
。
I don't know what your code is trying to accomplish - I'd guess you're trying to retrieve prices for products that a user is adding into their cart, but you're going about it in a very strange and highly inefficient manner.
我不知道您的代码要完成什么 - 我猜您正在尝试检索用户添加到购物车中的产品的价格,但是您以一种非常奇怪且效率极低的方式进行操作.