I am trying to create a simple cart system for my online shop. In order to store add the items the user selects to the cart, I have created an add to cart button under my items. My goal is that when this button is pressed the uid that is saved in my database, of the item selected is saved on a current session. However, when I press this button, for some reason it is always the id of the third item (cabuid 3) that gets saved onto the session, regardless of which item I add to cart. Here is my database
index.php file
<form style="border:1px solid #ccc" method="POST" enctype="multipart/form-data">
<?php
if (isset($_POST['add'])){
print_r($_POST['product_id']);
}
include __DIR__.'../includes/dbh.includes.php';
$sql = "SELECT * FROM boots";
$gotResults = mysqli_query($connection,$sql);
if($gotResults) {
if(mysqli_num_rows($gotResults)>0) {
while($row = mysqli_fetch_array($gotResults)){
?>
<div >
<div >
<div >
<img src="images/<?php echo $row['image']?>" style="width:100%">
<div >
<h2>
<?php echo $row['cabname']; ?> </h2>
<p><?php echo $row['cabdescription']; ?></p>
<p><?php echo $row['cabprice']; ?> € </p>
<p><button type="submit" name="add">Add to cart</button></p>
<input type='hidden' name='product_id' value="<?php echo $row['cabuid']; ?>">
</div>
</div>
</div>
<?php
}
}
}
?>
dbh.includes.php
<?php
$serverName = "localhost";
$dbUsername ="root";
$dbPassword ="";
$dbName = "webvacser";
$connection = mysqli_connect($serverName, $dbUsername, $dbPassword, $dbName);
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
?>
CodePudding user response:
I would make `n` forms, one per iteration of the loop
<?php
include __DIR__.'../includes/dbh.includes.php';
$sql = "SELECT * FROM boots";
$gotResults = mysqli_query($connection,$sql);
if($gotResults) {
if(mysqli_num_rows($gotResults)>0) {
while($row = mysqli_fetch_array($gotResults)){
?>
<div >
<div >
<div >
<img src="images/<?php echo $row['image']?>" style="width:100%">
<div >
<h2> <?php echo $row['cabname']; ?> </h2>
<p><?php echo $row['cabdescription']; ?></p>
<p><?php echo $row['cabprice']; ?> € </p>
<form style="border:1px solid #ccc" method="POST" enctype="multipart/form-data">
<p><button type="submit" name="add">Add to cart</button></p>
<input type='hidden' name='product_id' value="<?php echo $row['cabuid']; ?>">
</form>
</div>
</div>
</div>
<?php
}
}
}
?>
Now the 3 forms are unique and when you press the button inside any one of them the correct data from the associated hidden input will be sent to the receiving script