Hello I have created an add to cart function but when I click on add to cart it replace the previously added products
Here is my code
Header Area details.php
<?php
require_once("includes/functions.php");
if(isset($_POST["addtocart"])) {
$pid = $_POST["pid"];
$prod_name = $_POST["productname"];
$prod_price = $_POST["productprice"];
$category = $_POST["cat_name"];
if(isset($_POST['command']) == 'add' && $_POST['pid']>0 ) {
echo addtocart($pid,1, $prod_name, $prod_price, $category);
}
}
require_once("includes/header.php");
if (isset($_GET['pid'])) {
$pid = $_GET['pid'];
}
if(isset($_GET["cat"])) {
$category_name = mysqli_real_escape_string($connection, $_GET["cat"]);
}
?>
Content Area details.php
<div id="products-details"> <div class="row"> <?php
$result = mysqli_query($connection, "select * from products where prod_id='$pid'");
while ($row = mysqli_fetch_array($result)) {
$prod_name = $row['product_name'];
$prod_details = $row['description'];
$prod_price = $row['product_price'];
$prod_img = $row['product_image'];
$prod_id = $row['prod_id'];
}
?> <form method="POST" action="details.php"> <div class="col-md-4"> <img src="admin/uploads/<?php echo $prod_img; ?>" /> </div> <div class="col-md-8" style="background:#fff;"> <div class="heading1"> <h3><i class="fa fa-reorder"></i> <?php echo $category_name; ?> </h3> </div> <div class="product-descrip"> <h6> <?php echo $prod_name; ?> </h6> <p class="price">
$<?php echo $prod_price; ?> </p> <p class="description"> <?php
if(isset($prod_details)) {
echo $prod_details;
}
?> </p> <input type="hidden" name="productname" value="<?php echo $prod_name; ?>"/> <input type="hidden" name="productprice" value="<?php echo $prod_price; ?>"/> <input type="hidden" name="productid" value="<?php echo $prod_id?>"/> <input type="hidden" name="cat_name" value="<?php echo $category_name; ?>" /> <input type="hidden" name="command" value="add" /> <input type="hidden" name="pid" value="<?php echo $prod_id?>" /> <div class="btnadd"> <input type="submit" class="btn btn-default btnred" value="Add to Cart" name="addtocart" /> <a href="products.php?cat=<?php echo $category_name; ?>" class="btn btn-default btnred">Back</a> </div> </form> </div> </div>
and here is my addtocart function
function addtocart($pid,$q,$pname,$pprice){
if($pid<1 or $q<1) return;
if(is_array($_SESSION['cart'])){
if(product_exists($pid)) return;
$max=count($_SESSION['cart']);
$_SESSION['cart'][$max]['productid']=$pid;
$_SESSION['cart'][$max]['qty']=$q;
}
else{
$_SESSION['cart']=array();
$_SESSION['cart'][0]['productid']=$pid;
$_SESSION['cart'][0]['qty']=$q;
}
header("location:shoppingcart.php?pname=$pname&price=$pprice");
}
function product_exists($pid){
$pid=intval($pid);
$max=count($_SESSION['cart']);
$flag=0;
for($i=0;$i<$max;$i++){
if($pid==$_SESSION['cart'][$i]['productid']){
$flag=1;
break;
}
}
return $flag;
}