<?php
session_start();
连接
mysql_connect ('localhost', 'Akram', '') or die (mysql_error());
mysql_select_db('cart');
$page=("index.php");
数量
if (isset($_GET['add'])){
$quantity = mysql_query('SELECT id, quantity FROM products WHERE id='. mysql_real_escape_string((int)$_GET['add']));
while ($quantity_row = mysql_fetch_assoc($quantity)){
if ($quantity_row['quantity']!=$_SESSION['cart_'.$_GET['add']]){
$_SESSION['cart_'.$_GET['add']]+='1';
}
}
}
显示商品列表
function products (){
$get = mysql_query('SELECT * FROM products');
while ($row = mysql_fetch_assoc($get)){
echo '<p>' .$row ['name']. '</br>'.$row['price'].'</br>'.$row['quantity'].'<br/>'.$row['description']. '<br/>'.'<a href="cart.php?add='.$row['id'].'">'.'Add to cart'.'</a>'.'</p>';
}
}
在购物车中显示产品
function cart () {
foreach($_SESSION as $name => $value) {
if ($value>0) {
if (substr($name, 0,5)=='cart_') {
$id = substr($name, 5, (strlen ($name)-5));
$get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row ['price']*$value;
echo $get_row['name'] . ' X ' . $value . ' @ £' . number_format($get_row['price'], 2) . ' = ' . '£'.number_format($sub, 2). '<a href="cart.php?remove='.$id.'">'.'[REMOVE]'.'</a>'. '<a href="cart.php?add='.$id.'">'.'[ADD]'.'</a>'. '<a href="cart.php?delete='.$id.'">'.'[DELETE]'.'</a>';
}
}
$total += $sub; //getting error Undefined variable
}
}
if ($total==0) { //getting error Undefined variable
echo "your cart is empty!";
}
else {
echo 'Total: £'. number_format($total, 2);
//PayPal Button here
}
}
添加,删除和删除按钮
if(isset($_GET['add'])){
$_SESSION['cart_' .(int)$_GET['add']]+='1';
header('Location: ' .$page);
}
if (isset($_GET['remove'])){
$_SESSION['cart_' . (int)$_GET['remove']]--;
header('Location: ' .$page);
}
if (isset($_GET['delete'])){
$_SESSION['cart_' .(int)$_GET['delete']]='0';
header('Location: ' .$page);
}
?>
我试图在将所有项目添加到存储桶中之后得到所有项目的总价格但我使用$ total var进行未定义的变量错误。
答案 0 :(得分:0)
$total += $sub
在错误的地方出现了问题。
您应该将其移动到mysql_fetch中,以便总数适用于查询中的每个项目。
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row ['price']*$value;
echo $get_row['name'] . ' X ' . $value . ' @ £' . number_format($get_row['price'], 2) . ' = ' . '£'.number_format($sub, 2). '<a href="cart.php?remove='.$id.'">'.'[REMOVE]'.'</a>'. '<a href="cart.php?add='.$id.'">'.'[ADD]'.'</a>'. '<a href="cart.php?delete='.$id.'">'.'[DELETE]'.'</a>';
$total += $sub; //added it here
}
您还应该将$total
初始化为0,因此当查询中没有项目时(即购物车中没有商品),它会说购物车中没有商品。
类似于:
function cart () {
$total = 0;
这将解决您以后出现未设置变量的问题:
if ($total==0) { //getting error Undefined variable
echo "your cart is empty!";
}