2013-09-23 56 views
0

我只是在這裏新的PHP和即時嘗試創建一個簡單的購物車..但每次我運行代碼,發生錯誤。它說:「注意:未定義的變量:在372行的C:\ wamp \ www \ irm \ cart.php中的總數」。這裏是我的代碼:如何在php中解決「undefined variable:total」?

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

定義變量。 – Mihai

回答

3

這是因爲在使用它之前沒有定義它。與你的函數的頂部值零申報,以便它始終定義:

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

聲明一個變量並分配值0最初或使用isset()檢查變量設置或不

0

你必須初始化$ total,然後才能在表達式中使用它。你可以像這樣初始化它:

$total = null; 

此外你的代碼缺少結束大括號。您還可以回蜱不應該存在:

$_SESSION as $name`` => $value 
0

你必須定義函數中的變量$total,並給它一個零值。

function cart() { 
    $total = 0; 

    /* ... */ 
}