2013-04-16 4 views
-4

У меня возникли проблемы с этимНеопределенная переменная: общая

$total += $rows['price'] * $qty; 

Notice: Undefined переменной: всего в D: \ XAMPP \ HTDOCS \ WBPL-MusicLightDev \ вкл \ functions.inc.php на линии 42

function wbpl_showCart() { 
    global $db; 
    $cart = $_SESSION['cart']; 
    if ($cart) { 
     $items = explode(',', $cart); 
     //$contents = array(); 
     foreach ($items as $item) { 
      $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1; 
     } 
     echo '<form action="index.php?page=cart&action=update" method="post" id="cart">'; 
     echo '<table border=0 align="center" class="table table-bordered">'; 


     foreach ($contents as $id => $qty) { 
      $sql = "SELECT * from wbpl_product WHERE kd_product = '$id'"; 
      $result = mysql_query($sql) or die(mysql_error()); 
      $rows=mysql_fetch_array($result); 
      //extract($row); 

      echo '<tr> 
         <td>Brand</td> 
         <td colspan="4">'. $rows['kd_product'] .'</td> 
        <tr> 
        <tr> 
         <td>Brand</td> 
         <td colspan="4">'. $rows['nama_brand'] .'</td> 
        <tr> 
        <tr> 
          <td>Instrument Type</td> 
          <td colspan="4">'. $rows['nama_instype'] .'</td> 
        </tr> 
        <tr"> 
        <td rowspan="2">Price</td> 
        <td rowspan="2">Rp. ' . $rows['price'] . '</td> 
        <td rowspan="2"><input type="text" name="qty' . $id . '" value="' . $qty . '" size="2" maxlength="3" /></td> 

        <td rowspan="2">Rp. ' . ($rows['price'] * $qty) . '</td> 

        <td><a href="index.php?page=cart&action=delete&id=' . $id . '" class="btn btn-danger">Hapus</a></td> 
        </tr> 
        <tr><td><br></td></tr>'; 
      $total += $rows['price'] * $qty; 
     } 
     echo '</table>'; 
     $qty = getQty(); 


     echo '<p>Sub Total: <strong> Rp. ' . $total . '</strong></p>'; 



     //session_register('totalbayar'); 
     $_SESSION['totalbayar'] = $total; 
     echo '<div><button type="submit" class="btn btn-primary">Update cart</button></div>'; 
     echo '</form>'; 
    } else { 
     echo '<p>Keranjang belanja masih kosong.</p>'; 
    } 
    //return join('', $output); 
} 
+0

у вас есть вопросы? –

ответ

2

Вы не можете добавить что-то к несуществующему значению; Первый вызов: null + = $ rows ['price'] * $ qty; Это невозможно, поэтому добавьте

$ total = 0;

перед вашей петлей foreach!

function wbpl_showCart() { 
    global $db; 
    $cart = $_SESSION['cart']; 
    if ($cart) { 
     $items = explode(',', $cart); 
     //$contents = array(); 
     foreach ($items as $item) { 
      $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1; 
     } 
     echo '<form action="index.php?page=cart&action=update" method="post" id="cart">'; 
     echo '<table border=0 align="center" class="table table-bordered">'; 

     $total = 0; 
     foreach ($contents as $id => $qty) { 
      $sql = "SELECT * from wbpl_product WHERE kd_product = '$id'"; 
      $result = mysql_query($sql) or die(mysql_error()); 
      $rows=mysql_fetch_array($result); 
      //extract($row); 

      echo '<tr> 
         <td>Brand</td> 
         <td colspan="4">'. $rows['kd_product'] .'</td> 
        <tr> 
        <tr> 
         <td>Brand</td> 
         <td colspan="4">'. $rows['nama_brand'] .'</td> 
        <tr> 
        <tr> 
          <td>Instrument Type</td> 
          <td colspan="4">'. $rows['nama_instype'] .'</td> 
        </tr> 
        <tr"> 
        <td rowspan="2">Price</td> 
        <td rowspan="2">Rp. ' . $rows['price'] . '</td> 
        <td rowspan="2"><input type="text" name="qty' . $id . '" value="' . $qty . '" size="2" maxlength="3" /></td> 

        <td rowspan="2">Rp. ' . ($rows['price'] * $qty) . '</td> 

        <td><a href="index.php?page=cart&action=delete&id=' . $id . '" class="btn btn-danger">Hapus</a></td> 
        </tr> 
        <tr><td><br></td></tr>'; 
      $total += $rows['price'] * $qty; 
     } 
     echo '</table>'; 
     $qty = getQty(); 


     echo '<p>Sub Total: <strong> Rp. ' . $total . '</strong></p>'; 



     //session_register('totalbayar'); 
     $_SESSION['totalbayar'] = $total; 
     echo '<div><button type="submit" class="btn btn-primary">Update cart</button></div>'; 
     echo '</form>'; 
    } else { 
     echo '<p>Keranjang belanja masih kosong.</p>'; 
    } 
    //return join('', $output); 
} 
0
$total = 0; 

и установить это, прежде чем использовать $ общей будет решить вопрос

0

$x += y подразумевает первое чтение переменной затем добавьте что-то, а затем (повторно) назначьте результат. Во время первой итерации вашего цикла foreach нет переменной $total для чтения с момента выполнения оператора +=, следовательно, это предупреждение.
Инициализировать переменную перед циклом.

$total = 0; 
foreach ($contents as $id => $qty) { 
    [...] 
    $total += something; 
1

Объявите $total переменный:

$total = 0; 

перед входом в Еогеаспе петлю

проблемы является:

$total += ...; означает добавить ... к значению $total, но $total ISN 't еще не определено на первой итерации через цикл, что вызывает уведомление.

0

Чтобы использовать оператор +=, вы должны уже определить левую переменную. Вы можете решить эту проблему путем инициализации $total до его $total += ... использования:

$total = 0; 
foreach (...) 
    $total += ... 

Это происходит потому, что $total += $x внутренне преобразуется в $total = $total + $x, поэтому первый раз, когда вы используете его, $total в неопределенной.

Смежные вопросы