我有一个循环运行的购物车脚本,但是当我尝试通过电子邮件发送时,我只允许我通过电子邮件发送9个项目超过9个项目,电子邮件只是空白。我被告知我应该将我的查询'SELECT * FROM books WHERE id = '.$id;
更改为将返回没有循环的所有项目的查询。这是正确的,我应该尝试做什么?如果是这样,有人能给我一个如何做到这一点的例子吗?
<?php
function showCarts() {
global $db;
$cart = $_SESSION['cart'];
if ($cart) {
$items = explode(',',$cart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$output[] = '<table style="border-width:1px; bordercolor="#0099FF"">';
$output[] = '<tr>';
$output[] = '<thead bgcolor="#0099FF">';
$output[] = '<th>Item</th>';
$output[] = '<th>Price</th>';
$output[] = '<th>Quantity</th>';
$output[] = '<th>Total</th>';
$output[] = '</thead>';
$output[] = '</tr>';
foreach ($contents as $id=>$qty) {
$sql = 'SELECT * FROM books WHERE id = '.$id;
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
$output[] = '<tr>';
$output[] = '<td>'.$title.' by '.$author.'</td>';
$output[] = '<td>$'.$price.'</td>';
$output[] = '<td>'.$qty.'</td>';
$output[] = '<td>$'.($price * $qty).'</td>';
$total += ($price * $qty);
$output[] = '</tr>';
}
$output[] = '</table>';
$tax = (.07);
$taxtotal += round($total * $tax,2);
$amounttotal += ($total + $taxtotal);
$output[] = '<p>Tax: <strong>$'.$taxtotal.'</strong></p>';
$output[] = '<p>Total: <strong>$'.$amounttotal.'</strong></p>';
}
return join('',$output);
}
?>
答案 0 :(得分:1)
用以下代码替换你的for循环部分:
$ids = implode(',', array_keys($contents));
$sql = 'SELECT * FROM books WHERE id IN ('. $ids . ')';
$result = $db->query($sql);
while($row = $result->fetch()) {
extract($row);
$qty = $contents[(int)$row['id']]; // assuming your `$row` is an associative array of result
$output[] = '<tr>';
$output[] = '<td>'.$title.' by '.$author.'</td>';
$output[] = '<td>$'.$price.'</td>';
$output[] = '<td>'.$qty.'</td>';
$output[] = '<td>$'.($price * $qty).'</td>';
$total += ($price * $qty);
$output[] = '</tr>';
}