I am new to PHP and i am making a shopping cart for my website. I want to add possibility to change the quantity of the item in same page. And to show items when I click on it.
<?php
session_start();
require 'connect.php';
require 'item.php';
if(isset($_GET['itemid'])){
$query = 'select * from items where itemid='.$_GET['itemid'];
$result = mysqli_query($mysqli,$query);
$items = mysqli_fetch_object($result);
$item = new Item();
$item->id = $items->itemid;
$item->name = $items->itemname;
$item->price = $items->price;
$item->quantity = 1;
// Check item is existing in cart
$index = -1;
$cart = unserialize(serialize($_SESSION['cart']));
for($i=0; $i<count($cart);$i++)
if($cart[$i]->id==$_GET['itemid'])
{
$index = $i;
break;
}
if($index==-1)
$_SESSION['cart'][]= $item;
else{
$cart[$index]->quantity++;
$_SESSION['cart'] = $cart;
}
}
//Delete item in cart
if(isset($_GET['index'])){
$cart = unserialize(serialize($_SESSION['cart']));
unset($cart[$_GET['index']]);
$cart = array_values($cart);
$_SESSION['cart'] = $cart;
}
?>
<table cellpadding="2" cellspacing="2" border="1" >
<tr>
<th>option</th>
<th>Id</th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Sub Total</th>
</tr>
<?php
$cart = unserialize(serialize($_SESSION['cart']));
$s = 0;
for($i=0; $i<count($cart);$i++){
$s += $cart[$i]->price* $cart[$i]->quantity;
?>
<tr>
<td><a href="cart.php?index=<?php echo $index; ?>" onclick="return confirm('Are you sure?')">Delete</a></td>
<td><?php echo $cart[$i]->id; ?></td>
<td><?php echo $cart[$i]->name; ?></td>
<td><?php echo $cart[$i]->price; ?></td>
<td><?php echo $cart[$i]->quantity; ?></td>
<td><?php echo $cart[$i]->price* $cart[$i]->quantity; ?></td>
</tr>
<?php
$index++;
}
?>
<tr>
<td colspan="5" align="right">Sum</td>
<td align="left" ><?php echo $s; ?></td>
</tr>
</table>
<br>
<a href="newfile.php">Continue Shopping</a>
A simple and quick fix would be adding a field in the form for "quantity" and passing a $_GET variable in php.
$item->quantity = $_GET['quantity'];