I'm just new here in php and im trying to create a simple shopping cart..but every time i run the code, an error occurred. it said "Notice: Undefined variable: total in C:\\wamp\\www\\irm\\cart.php on line 372". Here's my code:
function cart(){
echo "<table table border='1' cellpadding='10'>";
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 prod_id, prod_name, prod_price FROM products WHERE prod_id='.mysql_real_escape_string((int)$id));
while ($get_row = mysql_fetch_assoc($get)){
$sub = $get_row['prod_price']*$value;
echo "<tr><th>Product Name</th> <th>Quantity</th> <th>Price</th> <th>Total</th> <th>Increase</th> <th>Decrease</th> <th>Remove</th></tr>";
echo '<td>'.$get_row['prod_name'].'</td>';
echo '<td>'.$value.'</td>';
echo '<td>'.' PhP'.number_format($get_row['prod_price'], 2).'</td>';
echo '<td>'.' PhP'.number_format($sub, 2).'</td>';
echo '<td>'.'<a href="cart.php?remove='.$id.'">[-]</a>'.'</td>';
echo '<td>'.'<a href="cart.php?add='.$id.'">[+]</a>'.'</td>';
echo '<td>'.'<a href="cart.php?delete='.$id.'">[Delete]</a></td>';
}
}
$total += $sub;
}
}
if($total==0){
echo "Your cart is empty.";
}
else{
echo 'Total: PhP'.number_format($total, 2);
}
This is because you don't define it before you use it. Declare it with a value of zero at the top of your function so it is always defined:
function cart(){
$total = 0; // <-- what you need to add
声明变量并初始分配值0
或使用isset()
检查变量是否已设置
You must initialize $total before you can use it in an expression. You can initialize it like this:
$total = null;
Also Your code is missing the closing curly brace. You also have back ticks that should not be present:
$_SESSION as $name`` => $value
You will have to define the variable $total
within the function and it give it a zero value.
function cart() {
$total = 0;
/* ... */
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.