I am working on a cart that i am trying to build for a project but got some php error message; I have tried to sort myself same errors keep coming. The idea behind the cart is:
- The person select a shoe size from a dropdown list
-if the item id is not in the cart then, it is a new product...so it is added to the cart
-however if the id and the size are same then we increase the quantity related to that id.
<?php
$items = array(
array('id' => '1', 'desc' => 'Addidas Original FlipFlap','price' => 24.95, 'size'=>'424546'),
array('id' => '2', 'desc' => 'Reebok Filas','price' => 200, 'size'=>'323845'),
array('id' => '3', 'desc' => 'Songs of the Goldfish (2CD set)','price' => 19.99),
array('id' => '4', 'desc' => 'Simply JavaScript (SitePoint)', 'price' => 39.95)
);
session_start();
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
if (isset($_POST['action']) and $_POST['action'] == 'Buy') {
$size="";
//Get the values for the post and make sure they are integers
$pid = filter_var( $_POST['id'], FILTER_VALIDATE_INT, array('min_range'=> 1) );
$size = $_POST['doSize'];
if (isset($_SESSION['cart'][$pid], $size)) {
$_SESSION['cart'][$pid][$size]['quantity']++;
print_r($_SESSION['cart']);
}
else{
$_SESSION['cart'][$pid][$size]= array('id'=>$pid, 'size'=>$size, 'quantity'=>1);
print_r($_SESSION['cart']);
}
}//END POST
include'catalog.html.php';
//unset($_SESSION['cart']);
?>
HERE MY HTML
<!DOCTYPE html>
<head>
<title>Product catalog</title>
<meta http-equiv="content-type"
content="text/html; charset=utf-8" />
<style type="text/css">
table {
border-collapse: collapse;
}
td, th {
border: 1px solid black;
}
</style>
</head>
<body>
<p>Your cart contains <?php echo count($_SESSION['cart']);?> item(s).</p>
<p><a href="?cart">View your cart</a></p>
<table border="1">
<thead>
<tr>
<th>Item Description</th>
<th>Price</th>
<th>Size</th>
</tr>
</thead>
<tbody>
<?php foreach ($items as $item): ?>
<tr>
<td><?php echo $item['desc']; ?></td>
<td>
$<?php echo number_format($item['price'], 2); ?>
</td>
<td>
<form action="" method="post">
<?php if (isset($item['size'])) { ?>
<select name="doSize">
<?php foreach(str_split($item['size'], 2) as $size):?>
<option value="<?php echo $size;?>"><?php echo $size;?></option>
<?php endforeach;?>
</select>
<?php }?>
</td>
<td>
<div>
<input type="hidden" name="id" value="<?php echo $item['id']; ?>"/>
<input type="submit" name="action" value="Buy"/>
</div>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<p>All prices are in imaginary dollars.</p>
</body>
</html>
When i add new product all works good. the quantity increase and all...But when items are added up to 3 items i got the ERROR BELOW
Notice: Undefined offset: 38 in C:\wamp\www\shopping-cart\index.php on line 22
Notice: Undefined index: quantity in C:\wamp\www\shopping-cart\index.php on line 22.
I have tried to sort it out myself but same status. Could somebody help me find the issue and tell how to sort out?