I have the following php script:
<?php
session_start();
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;
}
$output[] = '<form action="cart.php?action=update" method="post" id="cart">';
$total=0;
echo 'you have following books';
echo '</br>';
$output[] = '<table>';
foreach ($contents as $id=>$qty) {
$sql = "SELECT * FROM books WHERE bcode ='$id'";
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
$output[] = '<tr>';
$a = $output[] = '<td> '.$bname.'</td>';
$output[] = '<td>'.$price.'rs.</td>';
$output[] = '<td>*'.$qty.'</td>';
'</br>';
$output[] = '<td>Rs.'.($price * $qty).'</td>';
$total += $price * $qty;
$output[] = '</tr>';
}
$output[] = '</table>';
$output[] = '<p>Grand total: <strong>Rs.'.$total.'</strong></p>';
$output[] = '</form>';
} else {
$output[] = '<p>You shopping cart is empty.</p>';
}
?>
Is there a way to store results of the foreach loop in variables? .i.e $a will contain book name, but if there are two books the value of $a gets overwritten by the next book?
You’re re-intialising
$ain every iteration of the loop.All you need to do is set it right at the end of the function, with, say, an implode on
$outputOr, if you don’t want the whole output, just use it as an array: