php - Why does variable say undefined? -
this says $total , $sub undefined $total += $sub. $sub declared in while loop , both $sub within function should local variable. why can't use it?
public function cart() { foreach($_session $name=>$value){ if (substr($name, 0, 5) == 'cart_') { if((int)$value > 0){ $id = substr($name, 5, (strlen($name)-5)); $st = $this->db->prepare("select id, name, price deals id=?"); $st->bindparam(1, $id); $st->execute(); while($cart_item = $st->fetch(pdo::fetch_obj)){ $sub = $cart_item->price*$value; echo $cart_item->name.' x '.$value.' @ '.$cart_item->price.' = '.$sub.' <a href="cart.php?add='.$id.'">[+]</a> <a href="cart.php?remove='.$id.'">[-]</a> <a href="cart.php?delete='.$id.'">[delete]</a><br/>'; } } } $total += $sub; } }
the $total
variable should initialized above foreach
. $sub
variable should initialized inside foreach
, @ top.
$total = 0; foreach ($_session $name => $value) { $sub = 0; ...
also, can move $total += $sub;
higher up, positioned below inner while
loop.
Comments
Post a Comment