我有这个购物车脚本在循环中运行,但是当我尝试发送电子邮件时,我只允许我发送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);
}
?>
将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>';
}