Cart not functioning properly

When I try to add a product into my cart it only displays the latest id from my database or it can “only” display 1 id and when i try to remove 1 product from cart it removes all of them
Heres my code:

<?php
session_start();
$connect = mysqli_connect("localhost", "root", "", "meian");
if(isset($_POST["add"]))
{
	if(isset($_SESSION["cart"]))
	{
		$item_array_id = array_column($_SESSION["cart"], "product_id");
		if(!in_array($_GET["id"], $item_array_id))
		{
			$count = count($_SESSION["cart"]);
			$item_array = array(
				'product_id' => $_GET["id"],
				'item_name' => $_POST["hidden_name"],
				'product_price' => $_POST["hidden_price"],
				'item_quantity' => $_POST["quantity"]
			);
			$_SESSION["cart"][$count] = $item_array;
			echo '<script>window.location="shop.php"</script>';
		}
			echo '<script>alert("Product already added")</script>';
			echo '<script>window.location="shop.php"</script>';
	}
	else
		{
			$item_array = array(
				'product_id' => $_GET["id"],
				'item_name' => $_POST["hidden_name"],
				'product_price' => $_POST["hidden_price"],
				'item_quantity' => $_POST["quantity"]
			);
			$_SESSION["cart"][0] = $item_array;
		}
	}
	if(isset($_GET["action"]))
	{
		if($_GET["action"] == "delete")
		{
			foreach($_SESSION["cart"] as $keys => $values)
			{
				if($values["product_id"] == $_GET["id"])
				{
					unset($_SESSION["cart"][$keys]);
					echo '<script>alert("Product has been removed")</script>';
					echo '<script>window.location="shop.php"</script>';
				}
			}
		}
	}
?>



<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Shop</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link href="https://fonts.googleapis.com/css?family=Poppins:200,300,400,500,600,700,800&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Lora:400,400i,700,700i&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Amatic+SC:400,700&display=swap" rel="stylesheet">

    <link rel="stylesheet" href="css/open-iconic-bootstrap.min.css">
    <link rel="stylesheet" href="css/animate.css">

    <link rel="stylesheet" href="css/owl.carousel.min.css">
    <link rel="stylesheet" href="css/owl.theme.default.min.css">
    <link rel="stylesheet" href="css/magnific-popup.css">

    <link rel="stylesheet" href="css/aos.css">

    <link rel="stylesheet" href="css/ionicons.min.css">

    <link rel="stylesheet" href="css/bootstrap-datepicker.css">
    <link rel="stylesheet" href="css/jquery.timepicker.css">


    <link rel="stylesheet" href="css/flaticon.css">
    <link rel="stylesheet" href="css/icomoon.css">
    <link rel="stylesheet" href="css/style.css">
  </head>
   <body class="goto-here">
		<div class="py-1 bg-primary">
    	<div class="container">
    		<div class="row no-gutters d-flex align-items-start align-items-center px-md-0">
	    		<div class="col-lg-12 d-block">
		    		<div class="row d-flex">
		    			<div class="col-md pr-4 d-flex topper align-items-center">
					    	<div class="icon mr-2 d-flex justify-content-center align-items-center"><span class="icon-phone2"></span></div>
						    <span class="text">+639 876 543 210</span>
					    </div>
					    <div class="col-md pr-4 d-flex topper align-items-center">
					    	<div class="icon mr-2 d-flex justify-content-center align-items-center"><span class="icon-paper-plane"></span></div>
						    <span class="text">[email protected]</span>
					    </div>
					    <div class="col-md-5 pr-4 d-flex topper align-items-center text-lg-right">
						    <span class="text"></span>
					    </div>
				    </div>
			    </div>
		    </div>
		  </div>
    </div>
    <nav class="navbar navbar-expand-lg navbar-dark ftco_navbar bg-dark ftco-navbar-light" id="ftco-navbar">
	    <div class="container">
	      <a class="navbar-brand" href="index.html">MEIAN</a>
	      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#ftco-nav" aria-controls="ftco-nav" aria-expanded="false" aria-label="Toggle navigation">
	        <span class="oi oi-menu"></span> Menu
	      </button>

	      <div class="collapse navbar-collapse" id="ftco-nav">
	        <ul class="navbar-nav ml-auto">
	          <li class="nav-item active"><a href="index.html" class="nav-link">Home</a></li>
	          <li class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" href="#" id="dropdown04" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Shop</a>
              <div class="dropdown-menu" aria-labelledby="dropdown04">
              	<a class="dropdown-item" href="shop.html">Shop</a>
                <a class="dropdown-item" href="cart.html">Cart</a>
                <a class="dropdown-item" href="checkout.html">Checkout</a>
              </div>
            </li>
	          <li class="nav-item"><a href="about.html" class="nav-link">About</a></li>
	          <li class="nav-item"><a href="contact.html" class="nav-link">Contact</a></li>
	          <li class="nav-item cta cta-colored"><a href="cart.html" class="nav-link"><span class="icon-shopping_cart"></span>[0]</a></li>

	        </ul>
	      </div>
	    </div>
	  </nav>

    <div class="hero-wrap hero-bread" style="background-image: url('images/hehi.gif');">
      <div class="container">
        <div class="row no-gutters slider-text align-items-center justify-content-center">
          <div class="col-md-9 ftco-animate text-center">
          	<p class="breadcrumbs"><span class="mr-2"><a href="index.html">Home</a></span> <span>Products</span></p>
            <h1 class="mb-0 bread">Products</h1>
          </div>
        </div>
      </div>
    </div>

    <section class="ftco-section">
    	<div class="container">
    		<div class="row justify-content-center">
    			<div class="col-md-10 mb-5 text-center">
    				<ul class="product-category">
    					<li><a href="#" class="active">All</a></li>
    					<li><a href="#">Ice-cream</a></li>
    					<li><a href="#">Pastries</a></li>
    					<li><a href="#">Frappé</a></li>
    					<li><a href="#">Coffee</a></li>
    				</ul>
    			</div>
    		</div>

    		<div class="row">
          <?php
         $query = "SELECT * FROM product2 ORDER BY id ASC";
         $result = mysqli_query($connect, $query);
         if(mysqli_num_rows($result) > 0)
         {
           while($row = mysqli_fetch_array($result))
           {
     ?>
    			<div class="col-md-6 col-lg-3 ftco-animate">
    				<div class="product">

              <form method="post" action="shop.php?action=add&id=<?php echo $row["id"]; ?>">

    					<class="img-prod"><img src="<?php echo $row["image"]; ?>"  class="img-fluid">
    						<span class="status"></span>
    						<div class="overlay"></div>

    					<div class="text py-3 pb-4 px-3 text-center">
    						<h3><?php echo $row["pname"]; ?></h3>
    						<div class="d-flex">
    							<div class="pricing">
		    						<p class="price"><span class="price-sale">P <?php echo $row["price"]; ?></span></p>
		    					</div>
	    					</div>
	    					<div class="bottom-area d-flex px-3">
	    						<div class="m-auto d-flex">
                    <input type="text" align="center" name="quantity" class="form-control" value="1" size="1">
                    <input type="hidden" name="hidden_name" value="<?php echo $row["pname"]; ?>">
                    <input type="hidden" name="hidden_price" value="<?php echo $row["price"]; ?>">

	    							<input type="submit" name="add"  value="Add to Cart">


    							</div>
    						</div>
    					</div>
    				</div>
    			</div>
        <?php
      }
    }
       ?>

    	</div>
    </section>

	<section class="ftco-section ftco-cart">
				<div class="row">
    			<div class="col-md-12 ftco-animate">
    				<div class="cart-list">
	    				<table class="table">
						    <thead class="thead-primary">
						      <tr class="text-center">
						        <th>&nbsp;</th>
						        <th>&nbsp;</th>
						        <th>Product name</th>
						        <th>Price</th>
						        <th>Quantity</th>
                    <th>Price Detail</th>
                    <th>&nbsp;</th>

						      </tr>
						    </thead>

                <?php
                if(!empty($_SESSION["cart"]))
                {
                  $total = 0;
                  foreach($_SESSION["cart"] as $keys => $values)
                  {
                     ?>

						    <tbody>
						      <tr class="text-center">
						        <td class="product-remove"><a href="shop.php?action=delete&id=<?php echo $values["product_id"]; ?>"><span class="ion-ios-close"></span></a></td>

                  <td class="image-prod"><div class="img" style="background-image:url(images/product-3.jpg);"></div></td>

						        <td class="product-name">
						        	<h3><?php echo $values["item_name"]; ?></h3>
						        </td>

						        <td class="price">P <?php echo $values["product_price"]; ?></td>

						        <td class="quantity">
					             	<?php echo $values["item_quantity"]; ?>
					          </td>

                    <td class="total">P <?php echo number_format($values["item_quantity"] * $values["product_price"], 2); ?></td>





						      </tr>
                  <?php
                }
                 ?>

						    </tbody>
						  </table>
					  </div>
    			</div>

          <?php
          $total = $total * ($values["item_quantity"] * $values["product_price"]);
          }
          ?>



              <div class="col-md-12 d-flex mb-5">
                <div class="cart-detail cart-total p-3 p-md-4">
                  <h3 class="billing-heading mb-4">Cart Total</h3>
                  <hr>
                  <p class="d-flex total-price">
                    <span>Total</span>
                    <span>P <?php echo number_format($total, 2); ?></span>
                  </p>
                </div>
              </div>

    		</div>

    		</div>
			</div>

		</section>


    <section class="ftco-section">
      <div class="container">
        <div class="row justify-content-center">
          <div class="col-xl-7 ftco-animate">
						<form action="#" class="billing-form">
							<h3 class="mb-4 billing-heading">Delivery</h3>
	          	<div class="row align-items-end">
	          		<div class="col-md-6">
	                <div class="form-group">
	                	<label for="firstname">Firt Name</label>
	                  <input type="text" class="form-control" placeholder="">
	                </div>
	              </div>
	              <div class="col-md-6">
	                <div class="form-group">
	                	<label for="lastname">Last Name</label>
	                  <input type="text" class="form-control" placeholder="">
	                </div>
                </div>
                <div class="w-100"></div>
		            <div class="col-md-12">
		            	<div class="form-group">
		            		<label for="country">State / Country</label>
		            		<div class="select-wrap">
		                  <div class="icon"><span class="ion-ios-arrow-down"></span></div>
		                  <select name="" id="" class="form-control">
		                  	<option value="">France</option>
		                    <option value="">Italy</option>
		                    <option value="">Philippines</option>
		                    <option value="">South Korea</option>
		                    <option value="">Hongkong</option>
		                    <option value="">Japan</option>
		                  </select>
		                </div>
		            	</div>
		            </div>
		            <div class="w-100"></div>
		            <div class="col-md-6">
		            	<div class="form-group">
	                	<label for="streetaddress">Street Address</label>
	                  <input type="text" class="form-control" placeholder="House number and street name">
	                </div>
		            </div>
		            <div class="col-md-6">
		            	<div class="form-group">
	                  <input type="text" class="form-control" placeholder="Appartment, suite, unit etc: (optional)">
	                </div>
		            </div>
		            <div class="w-100"></div>
		            <div class="col-md-6">
		            	<div class="form-group">
	                	<label for="towncity">Town / City</label>
	                  <input type="text" class="form-control" placeholder="">
	                </div>
		            </div>
		            <div class="col-md-6">
		            	<div class="form-group">
		            		<label for="postcodezip">Postcode / ZIP *</label>
	                  <input type="text" class="form-control" placeholder="">
	                </div>
		            </div>
		            <div class="w-100"></div>
		            <div class="col-md-6">
	                <div class="form-group">
	                	<label for="phone">Phone</label>
	                  <input type="text" class="form-control" placeholder="">
	                </div>
	              </div>
	              <div class="col-md-6">
	                <div class="form-group">
	                	<label for="emailaddress">Email Address</label>
	                  <input type="text" class="form-control" placeholder="">
	                </div>
                </div>
                <div class="w-100"></div>
                <div class="col-md-12">
                	<div class="form-group mt-4">
									</div>
                </div>
	            </div>
	          </form>
					</div>
					<div class="col-xl-5">
	          <div class="row mt-5 pt-3">
	          	<div class="col-md-12 d-flex mb-5">
	          		<div class="cart-detail cart-total p-3 p-md-4">
	          			<h3 class="billing-heading mb-4">Cart Total</h3>
		    					<hr>
		    					<p class="d-flex total-price">
		    						<span>Total</span>
		    						<span>$17.60</span>
		    					</p>
								</div>
	          	</div>

									<p><a href="#"class="btn btn-primary py-3 px-4">Place an order</a></p>

	          	</div>
	          </div>
          </div>
        </div>
      </div>
    </section>

    <footer class="ftco-footer ftco-section">
      <div class="container">
      	<div class="row">
      		<div class="mouse">
						<a href="#" class="mouse-icon">
							<div class="mouse-wheel"><span class="ion-ios-arrow-up"></span></div>
						</a>
					</div>
      	</div>


            <p>
						  Copyright &copy;<script>document.write(new Date().getFullYear());</script> All rights reserved
						</p>
          </div>
        </div>
      </div>
    </footer>



  <!-- loader -->
  <div id="ftco-loader" class="show fullscreen"><svg class="circular" width="48px" height="48px"><circle class="path-bg" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke="#eeeeee"/><circle class="path" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke-miterlimit="10" stroke="#F96D00"/></svg></div>


  <script src="js/jquery.min.js"></script>
  <script src="js/jquery-migrate-3.0.1.min.js"></script>
  <script src="js/popper.min.js"></script>
  <script src="js/bootstrap.min.js"></script>
  <script src="js/jquery.easing.1.3.js"></script>
  <script src="js/jquery.waypoints.min.js"></script>
  <script src="js/jquery.stellar.min.js"></script>
  <script src="js/owl.carousel.min.js"></script>
  <script src="js/jquery.magnific-popup.min.js"></script>
  <script src="js/aos.js"></script>
  <script src="js/jquery.animateNumber.min.js"></script>
  <script src="js/bootstrap-datepicker.js"></script>
  <script src="js/scrollax.min.js"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false"></script>
  <script src="js/google-map.js"></script>
  <script src="js/main.js"></script>

  </body>
</html>

Well there are some problems with your code.

  1. You should not mess around with super globals like $_GET, $_POST and $_SESSION everywhere in your code. You dont know IF they exist…
  2. Never put sensitive data in forms that you have in the database like product prices. It is way too simple to change the prices in hidden form fields! Want to give your customers a lot of reduction?
  3. You can use the product ids as array keys. That would make your logic much easier.
<?php
session_start();
$connect = mysqli_connect("localhost", "root", "", "meian");

$cart = []; // assign an empty array to $cart by default
if(isset($_SESSION["cart"])) { // IF there is cart data in the session THEN ...
    $cart = $_SESSION["cart"]; // load complete cart data from session
}
// From here we know for sure that we have an existing $cart variable and that it is an array!

$product_id = 0;
if(isset($_GET["id"])) {
    $product_id =  (int) $_GET["id"]; // id of the product to add or delete
}
// From here we know for sure that we have an existing $product_id variable and that it is a integer!

// add or update a product to the cart
if(isset($_POST["add"]))
{
    // now get the trustable data like prices from the database and not from the POST array
    $result = $mysqli_query("SELECT id, name, price FROM products WHERE id=" . $product_id);
    if($result === false) {
        die('query is not valid');
    }
    
    $product = mysqli_fetch_assoc($result); // the product data that we need
    if($product === null) {
        die('no product found with id ' . $product_id);
    }

    // add or update product to cart
    $cart[$product_id] = array(
            'product_id' => $product_id,
            'item_name' => $product["name"], // get name from the database so that users cannot mess with it
            'product_price' => $product["price"],   // get price from the database so that users cannot mess with the prices either
            'item_quantity' => $_POST["quantity"]
    );
        
    // save cart to session
    $_SESSION['cart'] = $cart;
    
    // redirect
    header('Location: shop.php'); 
    exit;
} 

// remove a product from the cart
if(isset($_GET["action"]) && $_GET["action"] == "delete")
{
    unset($cart[$product_id]);
    
    // save cart to session
    $_SESSION['cart'] = $cart;
    
    // redirect
    header('Location: shop.php'); 
    exit;
}

?>

Alright i kinda did made the cart work but now when i try to add a product into cart it stills get only 1 kind of product repetitively from database and when i try to add 1 more product it doest add it

If you like you may sent the source or place it here if it is not too long

Here you go!

<?php
session_start();
$connect = mysqli_connect("localhost", "root", "", "meian");

$cart = []; // assign an empty array to $cart by default
if(isset($_SESSION["cart"])) { // IF there is cart data in the session THEN ...
    $cart = $_SESSION["cart"]; // load complete cart data from session
}
// From here we know for sure that we have an existing $cart variable and that it is an array!

$product_id = 0;
if(isset($_GET["id"])) {
    $product_id =  (int) $_GET["id"]; // id of the product to add or delete
}
// From here we know for sure that we have an existing $product_id variable and that it is a integer!

// add or update a product to the cart
if(isset($_POST["add"]))
{
    // now get the trustable data like prices from the database and not from the POST array
    $result = mysqli_query($connect, "SELECT id, pname, image, price FROM product2" , $product_id);
    if($result === false) {
        die('query is not valid');
    }

    $product = mysqli_fetch_assoc($result); // the product data that we need
    if($product === null) {
        die('no product found with id ' . $product_id);
    }

    // add or update product to cart
    $cart[$product_id] = array(
            'product_id' => $product_id["id"],
            'item_name' => $product["pname"], // get name from the database so that users cannot mess with it
            'product_price' => $product["price"],   // get price from the database so that users cannot mess with the prices either
            'item_quantity' => $_POST["quantity"],
            'image' => $_GET["image"]
    );

    // save cart to session
    $_SESSION['cart'] = $cart;

    // redirect
    header('Location: shop.php');
    exit;
}

// remove a product from the cart
if(isset($_GET["action"]) && $_GET["action"] == "delete")
{
    unset($cart[$product_id]);

    // save cart to session
    $_SESSION['cart'] = $cart;

    // redirect
    header('Location: shop.php');
    exit;
}

?>



<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Shop</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link href="https://fonts.googleapis.com/css?family=Poppins:200,300,400,500,600,700,800&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Lora:400,400i,700,700i&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Amatic+SC:400,700&display=swap" rel="stylesheet">

    <link rel="stylesheet" href="css/open-iconic-bootstrap.min.css">
    <link rel="stylesheet" href="css/animate.css">

    <link rel="stylesheet" href="css/owl.carousel.min.css">
    <link rel="stylesheet" href="css/owl.theme.default.min.css">
    <link rel="stylesheet" href="css/magnific-popup.css">

    <link rel="stylesheet" href="css/aos.css">

    <link rel="stylesheet" href="css/ionicons.min.css">

    <link rel="stylesheet" href="css/bootstrap-datepicker.css">
    <link rel="stylesheet" href="css/jquery.timepicker.css">


    <link rel="stylesheet" href="css/flaticon.css">
    <link rel="stylesheet" href="css/icomoon.css">
    <link rel="stylesheet" href="css/style.css">
  </head>
   <body class="goto-here">
		<div class="py-1 bg-primary">
    	<div class="container">
    		<div class="row no-gutters d-flex align-items-start align-items-center px-md-0">
	    		<div class="col-lg-12 d-block">
		    		<div class="row d-flex">
		    			<div class="col-md pr-4 d-flex topper align-items-center">
					    	<div class="icon mr-2 d-flex justify-content-center align-items-center"><span class="icon-phone2"></span></div>
						    <span class="text">+639 876 543 210</span>
					    </div>
					    <div class="col-md pr-4 d-flex topper align-items-center">
					    	<div class="icon mr-2 d-flex justify-content-center align-items-center"><span class="icon-paper-plane"></span></div>
						    <span class="text">[email protected]</span>
					    </div>
					    <div class="col-md-5 pr-4 d-flex topper align-items-center text-lg-right">
						    <span class="text"></span>
					    </div>
				    </div>
			    </div>
		    </div>
		  </div>
    </div>
    <nav class="navbar navbar-expand-lg navbar-dark ftco_navbar bg-dark ftco-navbar-light" id="ftco-navbar">
	    <div class="container">
	      <a class="navbar-brand" href="index.html">MEIAN</a>
	      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#ftco-nav" aria-controls="ftco-nav" aria-expanded="false" aria-label="Toggle navigation">
	        <span class="oi oi-menu"></span> Menu
	      </button>

	      <div class="collapse navbar-collapse" id="ftco-nav">
	        <ul class="navbar-nav ml-auto">
	          <li class="nav-item active"><a href="index.html" class="nav-link">Home</a></li>
	          <li class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" href="#" id="dropdown04" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Shop</a>
              <div class="dropdown-menu" aria-labelledby="dropdown04">
              	<a class="dropdown-item" href="shop.html">Shop</a>
                <a class="dropdown-item" href="cart.html">Cart</a>
                <a class="dropdown-item" href="checkout.html">Checkout</a>
              </div>
            </li>
	          <li class="nav-item"><a href="about.html" class="nav-link">About</a></li>
	          <li class="nav-item"><a href="contact.html" class="nav-link">Contact</a></li>
	          <li class="nav-item cta cta-colored"><a href="cart.html" class="nav-link"><span class="icon-shopping_cart"></span>[0]</a></li>

	        </ul>
	      </div>
	    </div>
	  </nav>

    <div class="hero-wrap hero-bread" style="background-image: url('images/hehi.gif');">
      <div class="container">
        <div class="row no-gutters slider-text align-items-center justify-content-center">
          <div class="col-md-9 ftco-animate text-center">
          	<p class="breadcrumbs"><span class="mr-2"><a href="index.html">Home</a></span> <span>Products</span></p>
            <h1 class="mb-0 bread">Products</h1>
          </div>
        </div>
      </div>
    </div>

    <section class="ftco-section">
    	<div class="container">
    		<div class="row justify-content-center">
    			<div class="col-md-10 mb-5 text-center">
    				<ul class="product-category">
    					<li><a href="#" class="active">All</a></li>
    					<li><a href="#">Ice-cream</a></li>
    					<li><a href="#">Pastries</a></li>
    					<li><a href="#">Frappé</a></li>
    					<li><a href="#">Coffee</a></li>
    				</ul>
    			</div>
    		</div>




    		<div class="row">
          <?php
         $query = "SELECT * FROM product2 ORDER BY id ASC";
         $result = mysqli_query($connect, $query);
         if(mysqli_num_rows($result) > 0)
         {
           while($row = mysqli_fetch_array($result))
           {
     ?>
    			<div class="col-md-6 col-lg-3 ftco-animate">
    				<div class="product">

              <form method="post" action="shop.php?action=add&id=<?php echo $row["id"]; ?>">

    					<class="img-prod"><img src="<?php echo $row["image"]; ?>"  class="img-fluid">
    						<span class="status"></span>
    						<div class="overlay"></div>

    					<div class="text py-3 pb-4 px-3 text-center">
    						<h3><?php echo $row["pname"]; ?></h3>
    						<div class="d-flex">
    							<div class="pricing">
		    						<p class="price"><span class="price-sale">P <?php echo $row["price"]; ?></span></p>
		    					</div>
	    					</div>
	    					<div class="bottom-area d-flex px-3">
	    						<div class="m-auto d-flex">
                    <input type="text" align="center" name="quantity" class="form-control" value="1" size="1">
                    <input type="hidden" name="hidden_name" value="<?php echo $row["pname"]; ?>">
                    <input type="hidden" name="hidden_price" value="<?php echo $row["price"]; ?>">

	    							<input type="submit" name="add"  value="Add to Cart">


    							</div>
    						</div>
    					</div>
    				</div>
    			</div>
        <?php
      }
    }
       ?>

    	</div>
    </section>




	<section class="ftco-section ftco-cart">
				<div class="row">
    			<div class="col-md-12 ftco-animate">
    				<div class="cart-list">
	    				<table class="table">
						    <thead class="thead-primary">
						      <tr class="text-center">
						        <th>&nbsp;</th>
						        <th>&nbsp;</th>
						        <th>Product name</th>
						        <th>Price</th>
						        <th>Quantity</th>
                    <th>Price Detail</th>
                    <th>&nbsp;</th>

						      </tr>
						    </thead>

                <?php
                if(!empty($_SESSION["cart"]))
                {
                  $total = 0;
                  foreach($_SESSION["cart"] as $keys => $values)
                  {
                     ?>

						    <tbody>
						      <tr class="text-center">
						        <td class="product-remove"><a href="shop.php?action=delete&id=<?php echo $values["product_id"]; ?>"><span class="ion-ios-close"></span></a></td>

                  <td class="image-prod"><div class="img">
                  <?php echo $values["image"]; ?></div></td>

						        <td class="product-name">
						        	<h3><?php echo $values["item_name"]; ?></h3>
						        </td>

						        <td class="price">P <?php echo $values["product_price"]; ?></td>

						        <td class="quantity">
					             	<?php echo $values["item_quantity"]; ?>
					          </td>

                    <td class="total">P <?php echo number_format($values["item_quantity"] * $values["product_price"], 2); ?></td>





						      </tr>
                  <?php
                }
                 ?>

						    </tbody>
						  </table>
					  </div>
    			</div>

          <?php
          $total = $total * ($values["item_quantity"] * $values["product_price"]);
          }
          ?>



              <div class="col-md-12 d-flex mb-5">
                <div class="cart-detail cart-total p-3 p-md-4">
                  <h3 class="billing-heading mb-4">Cart Total</h3>
                  <hr>
                  <p class="d-flex total-price">
                    <span>Total</span>
                    <span>P <?php echo number_format($total, 2); ?></span>
                  </p>
                </div>
              </div>

    		</div>

    		</div>
			</div>

		</section>


    <section class="ftco-section">
      <div class="container">
        <div class="row justify-content-center">
          <div class="col-xl-7 ftco-animate">
						<form action="#" class="billing-form">
							<h3 class="mb-4 billing-heading">Delivery</h3>
	          	<div class="row align-items-end">
	          		<div class="col-md-6">
	                <div class="form-group">
	                	<label for="firstname">Firt Name</label>
	                  <input type="text" class="form-control" placeholder="">
	                </div>
	              </div>
	              <div class="col-md-6">
	                <div class="form-group">
	                	<label for="lastname">Last Name</label>
	                  <input type="text" class="form-control" placeholder="">
	                </div>
                </div>
                <div class="w-100"></div>
		            <div class="col-md-12">
		            	<div class="form-group">
		            		<label for="country">State / Country</label>
		            		<div class="select-wrap">
		                  <div class="icon"><span class="ion-ios-arrow-down"></span></div>
		                  <select name="" id="" class="form-control">
		                  	<option value="">France</option>
		                    <option value="">Italy</option>
		                    <option value="">Philippines</option>
		                    <option value="">South Korea</option>
		                    <option value="">Hongkong</option>
		                    <option value="">Japan</option>
		                  </select>
		                </div>
		            	</div>
		            </div>
		            <div class="w-100"></div>
		            <div class="col-md-6">
		            	<div class="form-group">
	                	<label for="streetaddress">Street Address</label>
	                  <input type="text" class="form-control" placeholder="House number and street name">
	                </div>
		            </div>
		            <div class="col-md-6">
		            	<div class="form-group">
	                  <input type="text" class="form-control" placeholder="Appartment, suite, unit etc: (optional)">
	                </div>
		            </div>
		            <div class="w-100"></div>
		            <div class="col-md-6">
		            	<div class="form-group">
	                	<label for="towncity">Town / City</label>
	                  <input type="text" class="form-control" placeholder="">
	                </div>
		            </div>
		            <div class="col-md-6">
		            	<div class="form-group">
		            		<label for="postcodezip">Postcode / ZIP *</label>
	                  <input type="text" class="form-control" placeholder="">
	                </div>
		            </div>
		            <div class="w-100"></div>
		            <div class="col-md-6">
	                <div class="form-group">
	                	<label for="phone">Phone</label>
	                  <input type="text" class="form-control" placeholder="">
	                </div>
	              </div>
	              <div class="col-md-6">
	                <div class="form-group">
	                	<label for="emailaddress">Email Address</label>
	                  <input type="text" class="form-control" placeholder="">
	                </div>
                </div>
                <div class="w-100"></div>
                <div class="col-md-12">
                	<div class="form-group mt-4">
									</div>
                </div>
	            </div>
	          </form>
					</div>
					<div class="col-xl-5">
	          <div class="row mt-5 pt-3">
	          	<div class="col-md-12 d-flex mb-5">
	          		<div class="cart-detail cart-total p-3 p-md-4">
	          			<h3 class="billing-heading mb-4">Cart Total</h3>
		    					<hr>
		    					<p class="d-flex total-price">
		    						<span>Total</span>
		    						<span>$17.60</span>
		    					</p>
								</div>
	          	</div>

									<p><a href="#"class="btn btn-primary py-3 px-4">Place an order</a></p>

	          	</div>
	          </div>
          </div>
        </div>
      </div>
    </section>

    <footer class="ftco-footer ftco-section">
      <div class="container">
      	<div class="row">
      		<div class="mouse">
						<a href="#" class="mouse-icon">
							<div class="mouse-wheel"><span class="ion-ios-arrow-up"></span></div>
						</a>
					</div>
      	</div>


            <p>
						  Copyright &copy;<script>document.write(new Date().getFullYear());</script> All rights reserved
						</p>
          </div>
        </div>
      </div>
    </footer>



  <!-- loader -->
  <div id="ftco-loader" class="show fullscreen"><svg class="circular" width="48px" height="48px"><circle class="path-bg" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke="#eeeeee"/><circle class="path" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke-miterlimit="10" stroke="#F96D00"/></svg></div>


  <script src="js/jquery.min.js"></script>
  <script src="js/jquery-migrate-3.0.1.min.js"></script>
  <script src="js/popper.min.js"></script>
  <script src="js/bootstrap.min.js"></script>
  <script src="js/jquery.easing.1.3.js"></script>
  <script src="js/jquery.waypoints.min.js"></script>
  <script src="js/jquery.stellar.min.js"></script>
  <script src="js/owl.carousel.min.js"></script>
  <script src="js/jquery.magnific-popup.min.js"></script>
  <script src="js/aos.js"></script>
  <script src="js/jquery.animateNumber.min.js"></script>
  <script src="js/bootstrap-datepicker.js"></script>
  <script src="js/scrollax.min.js"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false"></script>
  <script src="js/google-map.js"></script>
  <script src="js/main.js"></script>

  </body>
</html>

What do you think this does and what should it be doing; before I go into anything?

if(isset($_POST["add"]))
{
    // now get the trustable data like prices from the database and not from the POST array
    $result = mysqli_query($connect, "SELECT id, pname, image, price FROM product2" , $product_id);
    if($result === false) {
        die('query is not valid');
    }

    $product = mysqli_fetch_assoc($result); // the product data that we need
    if($product === null) {
        die('no product found with id ' . $product_id);
    }

    // add or update product to cart
    $cart[$product_id] = array(
            'product_id' => $product_id["id"],
            'item_name' => $product["pname"], // get name from the database so that users cannot mess with it
            'product_price' => $product["price"],   // get price from the database so that users cannot mess with the prices either
            'item_quantity' => $_POST["quantity"],
            'image' => $_GET["image"]
    );

    // save cart to session
    $_SESSION['cart'] = $cart;

    // redirect
    header('Location: shop.php');
    exit;
}

It gets the data from my database so i can call it off, but it really doesnt want to work with me or im just too dumb

So, that won’t work, fyi: https://www.w3schools.com/php/func_mysqli_query.asp

mysqli_query( connection,query,resultmode ) ;
|Parameter|Description|
| — | — |
|connection|Required. Specifies the MySQL connection to use|
|query|Required. Specifies the query string|
|resultmode|Optional. A constant. Either:

  • MYSQLI_USE_RESULT (Use this if we have to retrieve large amount of data)
  • MYSQLI_STORE_RESULT (This is default)|

so should i just change all mysqli_query into mysqli_store_result?

A little working example. Has been tested this time.

If you want to have separate pages for each product e.g. product.php?id=5 then you should use the $_GET[‘id’] only to show the right product and not for the forms. In the forms you do everything with $_POST.

<?php
session_start();

$connect = mysqli_connect("127.0.0.1", "root", "password", "shop");
if (!$connect) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}

$cart = []; // assign an empty array to $cart by default
if (isset($_SESSION["cart"])) { // IF there is cart data in the session THEN ...
    $cart = $_SESSION["cart"]; // load complete cart data from session
}

// if it is a POST request
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    // add or update a product to the cart
    if (isset($_POST["add"])) {
        $product_id = (int) $_POST['id'];

        $result = mysqli_query($connect, "SELECT id, pname, image, price FROM products WHERE id=" . $product_id);

        if ($result === false) {

            die('query is not valid: ' . mysqli_error($connect));
        }

        $product = mysqli_fetch_assoc($result); // the product data that we need 

        if ($product === null) {

            die('no product found with id ' . $product_id);
        }


        // calculate total quantities
        $qty = $_POST["quantity"];
        if(isset($cart[$product_id])) {
            $qty = $cart[$product_id]['item_quantity'] + $qty;
        }

        // add or update product to cart
        $cart[$product_id] = array(
            'product_id' => $product_id,
            'item_name' => $product["pname"], // get name from the database so that users cannot mess with it
            'product_price' => $product["price"], // get price from the database so that users cannot mess with the prices either
            'item_quantity' => $qty,
            'image' => $_GET["image"]
        );
    }

    // remove a product from the cart
    if (isset($_POST["delete"])) {

        unset($cart[$_POST['id']]);
    }
    
    // save cart to session
    $_SESSION['cart'] = $cart;

    // redirect
    header('Location: shop.php');
    exit;
}

// show all products
$result = mysqli_query($connect, "SELECT id, pname, image, price FROM products");
if ($result === false) {

    die('query is not valid: ' . mysqli_error($connect));
}

?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Shop</title>
    </head>
    <body>
        <h1>cart</h1>
        <table>
            <?php foreach($cart as $item): ?>
                <tr>
                    <td><?php echo $item['item_quantity']; ?></td>
                    <td><?php echo $item['item_name']; ?></td>
                    <td><?php echo $item['product_price']; ?></td>
                    <td>
                        <form method="post">
                            <input type="hidden" value="<?php echo $item['product_id']; ?>" name="id">
                            <input type="submit" name="delete" value="Delete">
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
        </table>
        <h1>products</h1>
        <table>
            <?php while ($row = mysqli_fetch_assoc($result)): ?>
                <tr>
                    <td><?php echo $row['pname']; ?></td>
                    <td>
                        <form method="post">
                            <input type="hidden" value="<?php echo $row['id']; ?>" name="id">
                            <input type="number" value="1" name="quantity">
                            <input type="submit" name="add" value="Add">
                        </form>
                    </td>
                </tr>
            <?php endwhile; ?>
        </table>
    </body>
</html>

That’s not safe code and is a security risk to use.

Why not use a open source cart? Or is this JUST for learning?

I tried using your code and just replaced some stuffs and it gave me this

**Notice** : Undefined index: id in **C:\xampp\htdocs\meian\shop.php** on line **21**
no product found with id 0

It is just for learning, for now

tell us why if you would like to say something?

Maybe replaced a little too much?

I tried your code and it worked surprisingly im guessing theres a problem to my htmls

It is completely open to sql injection.
There is no separation of concerns.
You are using table for layout.
Using the connection string on the actual page.
Using to many details in the cart.

How much do you want me to pull apart? I was trying to be informative, but if you want me to say something, the code quality is about school level and is not meant for maintainability or actual deployment at all.

When i try to add a product into cart it says
no product found with id 0 any ideas?

t is completely open to sql injection.
Where? I know there are nicer ways but with an int there is not too much possible to inject

There is no separation of concerns.
I know. Dont miss understand me but i know for sure that its all way too complicated for the topic starter at this moment

You are using table for layout.
And? Less responsive but valid html

Using the connection string on the actual page.
Your right. Should be in a config file . I know that too.

Using to many details in the cart.
why?

It should be helpfull if you wrote those comments to the topic starter and and gave some examples or advise. I try to help and thanks to you i am done right now.

Sponsor our Newsletter | Privacy Policy | Terms of Service