我正在制作一个PHP购物车,我正在尝试添加总价。
当我想使用$ total时,我收到此错误:Undefined variable: total
。为什么这不起作用?我怎样才能使这个工作?
代码:
function cart() {
include 'dbh.inc.php';
foreach($_SESSION as $name => $value) {
if($value > 0) {
if(substr($name, 0,5)=='cart_') {
$id = substr($name, 5, strlen($name)-5);
$sql = "SELECT * FROM menuitem WHERE menuitem_id = '$id'";
$result = mysqli_query($conn, $sql);
while ($sqlResult = mysqli_fetch_assoc($result)) {
$sub = $sqlResult['price_medium'] * $value;
echo '
<td>' . $sqlResult['productname'] . '</td>
<td>' . $value . '</td>
<td>€ ' . $sqlResult['price_medium'] . '</td>
<td>€ ' . $sub . '</td>
<td><a href="includes/add-to-cart.inc.php?remove=' . $id . '">[-] </a><a href="includes/add-to-cart.inc.php?add=' . $id . '">[+] </a><a href="includes/add-to-cart.inc.php?delete=' . $id . '">[x]</a>
</tr>
';
}
}
$total += $sub;
}
}
echo $total;
}
为克里斯编辑:
我现在有了这个:
function cart() {
include 'dbh.inc.php';
foreach($_SESSION as $name => $value) {
if($value > 0) {
if(substr($name, 0,5)=='cart_') {
$id = substr($name, 5, strlen($name)-5);
$sql = "SELECT * FROM menuitem WHERE menuitem_id = '$id'";
$total = 0;
$result = mysqli_query($conn, $sql);
while ($sqlResult = mysqli_fetch_assoc($result)) {
$sub = $sqlResult['price_medium'] * $value;
echo '
<td>' . $sqlResult['productname'] . '</td>
<td>' . $value . '</td>
<td>€ ' . $sqlResult['price_medium'] . '</td>
<td>€ ' . $sub . '</td>
<td><a href="includes/add-to-cart.inc.php?remove=' . $id . '">[-] </a><a href="includes/add-to-cart.inc.php?add=' . $id . '">[+] </a><a href="includes/add-to-cart.inc.php?delete=' . $id . '">[x]</a>
</tr>
';
}
}
$total += $sub;
}
}
echo $total;
}