This says $total and $sub is undefined for $total += $sub. $sub was declared in the while loop and both $sub are within the function so it should be a local variable. Why can’t I use it?
public function cart() {
foreach($_SESSION as $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 from deals where 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
$totalvariable should be initialized above yourforeach. The$subvariable should be initialized inside theforeach, at the top.Also, you can move the
$total += $sub;higher up, to be positioned just below the innerwhileloop.