我正在开发一个简单的订单系统。
我所坚持的代码片段如下:
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();
}
这是构建在预设数组上的代码。在mysql中,我正在处理一个包含几列的表。
我决定了以下几点:
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();
}}
为了显示这个“购物车”,我决定这样做:
foreach ($cart as $item) {
$pageContent .= '
<tr>
<td>'.$item['desc'].'</td>
<td>
R'.number_format($item['price'], 2).'
</td>
</tr>
';
}
所有这一切似乎都是以一种方式生成我的购物车,当查看它时,它只显示商品id的列表,例如,在应该显示描述和价格的地方,我只在这两个字段中获得商品id……我也得到了0的总价。
有没有人能发现我哪里出了问题?
或者至少试着给我一些输入,这样我就可以朝着正确的方向前进!
谢谢!!
$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>
';
}}
发布于 2011-08-06 05:28:54
中间的代码块没有任何意义。您遍历会话变量,并在每次运行查询时...但这是相同的查询,并使用一个未定义的变量进行引导。循环遍历结果行没有多大意义,因为您将循环遍历查询为每行返回的各个字段。
例如,如果您的products表只有(id, name, description)
作为字段,那么$row
将是一个如下所示的数组:
$row = array('id' => xxx, 'name' => yyy, 'description' => zzz);
当你在$row()
上使用foreach()
时,你不会得到单独的产品,你会得到行中的那些字段。$product将是xxx
,然后是yyy
,然后是zzz
。
我不知道你的代码想要实现什么--我猜你是在试图检索用户添加到购物车中的产品的价格,但你却以一种非常奇怪和非常低效的方式来做这件事。
https://stackoverflow.com/questions/6962771
复制相似问题