PHP Shopping Cart list only one item
I am working on an onlinestore project. In my code,the shopping cart will only list 1 item. For example when i click add to cart button under iphone 5s it will jump to the cart and show me Iphone 5s with 1 quantity. However, when i press again Samsung, it will overwrite Iphone 5s and show me only Samsung.
Here is the code for product:
<div>
<image src="ip5s.jpg">
<p><font color="blue">  Iphone 5S</font></p>
<p><font color="red">  RM1999</font></p>
<p><form name="addcart" method="post" action="processcart.php">
<input type="submit" name="addtocart" value="Add to cart" >
<input type="hidden" name="product_id" value="1234" />
<input type="hidden" name="quantity" value="1" />
</form>
</p>
</div>
  
<div >
<image src="s4.png">
<p><font color="blue">  Samsung Galaxy S4</font></p>
<p><font color="red">  RM1999</font></p>
<p><form name="addcart" method="post" action="processcart.php" >
<input type="submit" name="addtocart" value="Add to cart">
<input type="hidden" name="product_id" value="1235" />
<input type="hidden" name="quantity" value="1" />
</form>
</p>
</div>
Here is the processcart.php:
<?php
session_start();
include_once("config.php");
$_SESSION['pid']=$_POST['product_id'];
$_SESSION['qty']+=$_POST['quantity'];
$_SESSION['cart']=true;
sleep(2);
echo "Add to cart successful";
header("refresh:1;url=cart.php");
exit();
?>
Here is the cart.php:
<?php
if (!isset($_SESSION['cart']))
echo "<p>Your shopping cart is empty!</p>";
elseif (isset($_SESSION['cart'])) {
define("DB_HOST", "localhost");
define("DB_NAME", "onlinestore");
define("DB_USER", "root");
define("DB_PASSWORD", "");
$tblname = "products";
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db(DB_NAME);
$proid = $_SESSION['pid'];
$query = "SELECT * from $tblname where product_id='$proid'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
echo "<table>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "<tr><td>" . $row['product_name'] . "</td><td>" . $row['product_price'] . "</td></tr>";
echo $_SESSION['qty'];
}
echo "</table>";
mysql_free_result($result);
mysql_close();
}
?>
Answer
Solution:
$_SESSION['pid']=$_POST['product_id'];
- this probably each time replaces product in the cart. Should be an array of products.Answer
Solution:
edit:
from
to
Then edit your processing to loop through the session & get each product.
Edit: You should consider using
$_SESSION['cart']['products'] = array();
as it makes more sense in the organisation side of your vars: Produacts are in the cart, and as such a part of your cart.edit2:
This is how I would organized cart, based on using $_SESSION['cart']['products'] for storing products. Note: Untested code; Will probably have some typos. Just go through it and try to understand the logic: