I am new to php. I coded so far the products page who fetch from database and now I want to start coding the "add to cart" button that sends items to a cart database table.
I really would appreciate if anyone can tell me where should I start. I tried so many ways and it failed to send data to cart. This is my code:
<div id="product-grid">
<div class="product-item">
<form method="post" action="add.php">
<input type="hidden" class="product-image" name="image"><img src="<?php echo $products[$i]["image"]; ?>">
<div class="product-tile-footer">
<input type="hidden" class="product-title" name="name"><b><?php echo $products[$i]["name"]; ?></b> <br>
<input type="hidden" class="product-price" name="price"><?php echo "$".$products[$i]["price"]; ?>
<div class="cart-action"><input type="text" class="product-quantity" name="quantity" value="1" size="2" />
<input type="submit" value="Add to Cart" name="add" class="btnAddAction"/></div>
</div>
</form>
</div>
</div>
<?php
}
?>
add.php
<?php
session_start();
$link = mysqli_connect("localhost", "root", "", "MyGym") or die("DB Connection error");
if(isset($_POST['add']))
{
$email=$_SESSION['email'];
$image = $_POST['image'];
$name = $_POST['name'];
$code=$_POST['code'];
$price = $_POST['price'];
$qty=$_POST['quantity'];
$sql = "INSERT INTO cart (email,image,name,code,price,quantity)
VALUES ('$email','$image','$name','$code','$price','$qty')";
if (mysqli_query($link, $sql)) {
echo "Added To cart !";
header("location:Store.php");
} else {
echo "Error: " . $sql . ":-" . mysqli_error($link);
}
mysqli_close($link);
}
?>