How to make add product to cart button to work

HELLO. So I followed the tutorial on how to create an commerce store with PHP.

I ran into a problem when I could not add products to the cart.
The problem is that when I click on the add product button, I am redirected to index.php instead of the cart

I’m learning php by self-study, so I’m not a specialist in all of this and sometimes to understand programming it’s easier to follow the tutorial

this is cart file

<?php
session_start();
include 'server/connection.php';
include 'layouts/header.php';

print_r($_POST); // Add this line

//if user has already added a product to cart
if (isset($_POST['add_cart_cart'])) {

	if (isset($_SESSION['cart'])) {

		$product_array_ids = array_column($_SESSION['cart'], "product_id"); // [2, 4, 10, 15 ]

		//if product has already been added to cart or not
		if (!in_array($_POST['product_id'], $product_array_ids)) {

			$product_array = array(
				'product_id' => $_POST['product_id'],
				'product_name' => $_POST['product_name'],
				'product_price' => $_POST['product_price'],
				'product_image' => $_POST['product_image'],
				'product_quantity' => $_POST['product_quantity'],

			);

			$_SESSION['cart'][$product_id] = $product_array;

//product has already been added
		} else {

			echo '<script>alert("Product was already added to cart");</script>';

		}

//if this is the first product

	} else {

		$product_id = $_POST['product_id'];
		$product_name = $_POST['product_name'];
		$product_price = $_POST['product_price'];
		$product_image = $_POST['product_image'];
		$product_quantity = $_POST['product_quantity'];

		$product_array = array(
			'product_id' => $product_id,
			'product_name' => $product_name,
			'product_price' => $product_price,
			'product_image' => $product_image,
			'product_quantity' => $product_quantity,

		);

		$_SESSION['cart'][$product_id] = $product_array; //[ 2 =>[] ,[ 3 =>[], [ 5 =>[] ]

	}

//remove product from cart
} else if (isset($_POST['remove_product'])) {

	$product_id = $_POST['product_id'];
	unset($_SESSION['cart'][$product_id]);

} else if (isset($_POST['edit_quantity'])) {

	//we got id and quantity from the form
	$product_id = $_POST['product_id'];
	$product_quantity = $_POST['product_quantity'];

	//get the product array from the session
	$product_array = $_SESSION['cart'][$product_id];

	//update product quantity
	$product_array['product_quantity'] = $product_quantity;

	//return array back to its place
	$_SESSION['cart'][$product_id] = $product_array;

	//calculate total
	calculateTotalCart();

} else {
	header('location: index.php');
}

function calculateTotalCart() {
	$total = 0;
	foreach ($_SESSION['cart'] as $key => $value) {
		$product = $_SESSION['cart'][$key];
		$price = $product['product_price'];
		$quantity = $product['product_quantity'];
		$subTotal = $price * $quantity;
		$total += $subTotal;
	}
	$_SESSION['total'] = $total;
}

?>

<section class="cart container my-5 py-5">
	<div class="container mt-5">
		<h2 class="font-weight-bolde">Your Cart</h2>
		<hr>
	</div>

	<table class="mt-5 pt-5">
		<tr>
			<th>Product</th>
			<th>Quality</th>
			<th>Subtotal</th>
		</tr>

		<?php foreach ($_SESSION['cart'] as $key => $value) {?>

		<tr>
			<td>
				<div class="product-info">
					<img src="assets/imgs/<?php echo $value['product_image']; ?>"/>
					<div>
						<p><?php echo $value['product_image']; ?></p>
						<small><span>€</span><?php echo $value['product_price']; ?></small>
						<br>
						<form method="POST" action="cart.php">

							<input type="hidden" name="product_id" value="<?php echo $key; ?>">

							<input type="submit" name="remove_product" class="remove-btn" value="remove"/>

						</form>
					</div>
				</div>
			</td>
			<td>
				<input type="number" value="<?php echo $value['product_quantity']; ?>"/>


				<a href="edit-btn" name="edit_quantity">edit</a>

			</td>
			<td>
				<span>€</span>
				<span class="product-price">20</span>
			</td>
		</tr>

	<?php }?>
	</table>

	<div class="cart-total">
		<table>
			<tr>
				<td>Subtotal</td>
				<td>€40</td>
			</tr>
			<tr>
				<td>Total</td>
				<td>€40</td>
			</tr>
		</table>
	</div>

	<div class="checkout-container">
		<button class="btn checkout-btn">Checkout</button>
	</div>
</section>

and this is single product file

<?php
session_start();
include 'server/connection.php';
include 'layouts/header.php';

if (isset($_GET['product_id'])) {
	$product_id = $_GET['product_id'];
	$stmt = $conn->prepare("SELECT * FROM products WHERE product_id = ?");
	$stmt->bind_param("i", $product_id);
	$stmt->execute();
	$product = $stmt->get_result();
} else {
	header('location: index.php');
}

?>



<!--single product--->
<section class="container single-product my-5 pt-5">
	<div class="row mt-5">

		<?php while ($row = $product->fetch_assoc()) {?>

		<div class="col-lg-5 col-md-6 col-sm-12">
               	<img class="img-fluid w-100 pb-1" src="assets/imgs/<?php echo $row['product_image']; ?>" id="mainImg"/>
                <div class="small-img-group">
				<div class="small-img-col">
                    <img src="assets/imgs/<?php echo $row['product_image']; ?>" width="100%" class="small-image">
                </div>
				<div class="small-img-col">
                    <img src="assets/imgs/<?php echo $row['product_image2']; ?>" width="100%" class="small-image">
                </div>
				<div class="small-img-col">
                    <img src="assets/imgs/<?php echo $row['product_image3']; ?>" width="100%" class="small-image">
                </div>
				<div class="small-img-col">
                    <img src="assets/imgs/<?php echo $row['product_image4']; ?>" width="100%" class="small-image">
                </div>
			</div>
		</div>



		<div class="col-lg-6 col-sd-12 col-sm-12">
			<h6>Woman/Clothes</h6>
			<h3 class="py-4"><?php echo $row['product_name']; ?></h3>
			<h2>€<?php echo $row['product_price']; ?></h2>

		<form method="POST" action="cart.php">
				<input type="hidden" name="product_id" value="<?php echo $row['product_id']; ?>">
				<input type="hidden" name="product_image" value="<?php echo $row['product_image']; ?>/">
				 <input type="hidden" name="product_name" value="<?php echo $row['product_name']; ?>/">
				 <input type="hidden" name="product_price" value="<?php echo $row['product_price']; ?>/">

				 <input type="number" name="product_quantity" value="1"/>
				  <button class="buy-btn" type="submit" name="add_to_cart">Add To Cart</button>
			</form>


			<h4 class="mt-5 mb-5">Product details</h4>
			<span><?php echo $row['product_description']; ?></span>
		</div>
		<?php }?>
	</div>
</section>



<!----Realeted products-->

<section id="realated-products" class="mt-5 pb-5">
		<div class="container text-center mt-5 py-5">
			<h3>Realeted products</h3>
			<hr class="mx-auto">
		</div>
		<div class="row mx-auto container-fluid">
			<div class="product text-center col-lg-3 col-md-4 col-sm-12">
				<img class="img-fluid mb-3" src="assets/imgs/featured1.jpeg"/>
				<div class="star">
		          <i class="fa fa-star" style="color: orange;"></i>
		          <i class="fa fa-star" style="color: orange;"></i>
		          <i class="fa fa-star" style="color: orange;"></i>
		          <i class="fa fa-star" style="color: orange;"></i>
		          <i class="fa fa-star" style="color: orange;"></i>
		        </div>
				<h5 class="p-name">T-shirt</h5>
				<h4 class="p-price">€20</h4>
				<button class="text-uppercase">Buy Now</button>
			</div>
			<div class="product text-center col-lg-3 col-md-4 col-sm-12">
				<img class="img-fluid mb-3" src="assets/imgs/featured2.jpeg"/>
				<div class="star">
		          <i class="fa fa-star" style="color: orange;"></i>
		          <i class="fa fa-star" style="color: orange;"></i>
		          <i class="fa fa-star" style="color: orange;"></i>
		          <i class="fa fa-star" style="color: orange;"></i>
		          <i class="fa fa-star" style="color: orange;"></i>
		        </div>
				<h5 class="p-name">T-shirt</h5>
				<h4 class="p-price">€20</h4>
				<button class="text-uppercase">Buy Now</button>
			</div>
			<div class="product text-center col-lg-3 col-md-4 col-sm-12">
				<img class="img-fluid mb-3" src="assets/imgs/featured3.jpeg"/>
					<div class="star">
		          <i class="fa fa-star" style="color: orange;"></i>
		          <i class="fa fa-star" style="color: orange;"></i>
		          <i class="fa fa-star" style="color: orange;"></i>
		          <i class="fa fa-star" style="color: orange;"></i>
		          <i class="fa fa-star" style="color: orange;"></i>
		        </div>
				<h5 class="p-name">Shoes</h5>
				<h4 class="p-price">€20</h4>
				<button class="text-uppercase">Buy Now</button>
			</div>
			<div class="product text-center col-lg-3 col-md-4 col-sm-12">
				<img class="img-fluid mb-3" src="assets/imgs/featured4.jpeg"/>
				<div class="star">
		          <i class="fa fa-star" style="color: orange;"></i>
		          <i class="fa fa-star" style="color: orange;"></i>
		          <i class="fa fa-star" style="color: orange;"></i>
		          <i class="fa fa-star" style="color: orange;"></i>
		          <i class="fa fa-star" style="color: orange;"></i>
		        </div>
				<h5 class="p-name">Shoes</h5>
				<h4 class="p-price">€20</h4>
				<button class="text-uppercase">Buy Now</button>
			</div>
		</div>
	</section>



<script>
    var mainImg = document.getElementById("mainImg");
    var smallImg = document.getElementsByClassName("small-img");

    for (let i = 0; i < 4; i++) {
        smallImg[i].onclick = function() {
            mainImg.src = smallImg[i].src;
        }
    }
</script>






<?php include 'layouts/footer.php';?>```

It might help if you said which tutorial…

Don’t attempt to detect if a submit button isset() to run post method form processing code. There are cases where it won’t be. You should instead detect if a post method form was submitted - if($_SERVER['REQUEST_METHOD'] === 'POST'){...}. If there is code for more than one post method form processing on a page, use a hidden field, such as name='action' with a unique value, such as add_to_cart, to control which form processing code to execute. You would generally use a switch/case statement to control which code to execute based on a value. Your existing else if(...) logic can be just be if(…) statements, because there will only ever be one value at a time.

The only array value you should store in the cart is the quantity. All the other values - image (of which you can have more than one), name, and price should not be stored in the cart, nor passed through the form, since this is not secure. You should query the database for them when needed.

You should not have a series of name-numbered columns in a database table. To allow any number of images per product, you should have a separate table for the image data, one row per product per image, related back to the product through the product_id.

As to why the current code is not working, the submit button is not named the same as what the php code is testing for. The print_r($_POST); output should have exposed this mistake.

1 Like

Sorry I forgot to mention but this

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.