1

我有这个循环运行的购物车脚本,但是当我尝试通过电子邮件发送它时,我只允许我通过电子邮件发送 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>&dollar;'.$price.'</td>';
    $output[] = '<td>'.$qty.'</td>';
    $output[] = '<td>&dollar;'.($price * $qty).'</td>';
    $total += ($price * $qty);
    $output[] = '</tr>';
}
$output[] = '</table>';
$tax = (.07);
$taxtotal += round($total * $tax,2);
$amounttotal += ($total + $taxtotal);
$output[] = '<p>Tax: <strong>&dollar;'.$taxtotal.'</strong></p>';
$output[] = '<p>Total: <strong>&dollar;'.$amounttotal.'</strong></p>';
}
return join('',$output);
}
?>
4

1 回答 1

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>&dollar;'.$price.'</td>';
      $output[] = '<td>'.$qty.'</td>';
      $output[] = '<td>&dollar;'.($price * $qty).'</td>';
      $total += ($price * $qty);
      $output[] = '</tr>';
    }
于 2013-05-30T02:29:23.667 回答