如何在php中解决“未定义的变量:总计”


How to solve "undefined variable : total" in php?

我只是 php 的新手,我试图创建一个简单的购物车。但是每次运行代码时,都会发生错误。 它说"注意:未定义的变量:C:''wamp''www''irm''cart.php 第 372 行中的总计"。这是我的代码:

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);
}

这是因为您在使用它之前没有定义它。在函数顶部用零值声明它,以便始终定义它:

function cart(){
    $total = 0; // <-- what you need to add

声明一个变量并分配值 0 或使用isset()来检查变量是否设置了

必须先初始化$total,然后才能在表达式中使用它。您可以像这样初始化它:

$total = null;

此外,您的代码缺少右大括号。您还有不应该出现的反勾号:

$_SESSION as $name`` => $value

您必须在函数中定义变量$total,并为其提供零值。

function cart() {
    $total = 0;
    /* ... */
}