I have created a form where every time, it would store a different id during foreach loop
<?php
foreach ($res as $r) {
?>
<form id="clearitem" action="clearitem.php" method="POST" enctype="multipart/form-data">
<input type="text" name="clearitem" value="<?php echo $r['cart_id'];?>">
<button type="Submit">×</button>
</form>
<?php
}
?>
and the retrieval of the data works perfectly, it shows me each and every id one after another, but when I click the button (in this case to clear the item) it only works for the first value i.e. if I click the button for the second or the third value, it deletes the first one only, not the one corresponding to the button.
please do help, why this is happening and the appropriate solution, if anyone can provide!
the clearitem.php
if(isset($_POST['clearitem'])){
$clear=$_POST['clearitem'];
$sql = "DELETE FROM cart WHERE id=".$clear;
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully of id".$clear;
} else {
echo "Error deleting record: " . $conn->error;
}
}
CodePudding user response:
The system should be able to correctly process the submitted data according to the data value in each form
in such a "multi-form" environment.
Hence the code below should work (tested):
<?php
$conn = new mysqli("localhost","dbuser","dbpassword","dbname");
$sql = "SELECT * FROM cart";
$stmt = $conn->prepare($sql);
$stmt->execute();
$res = $stmt->get_result();
foreach ($res as $r) {
?>
<form id="clearitem" action="clearitem.php" method="POST" enctype="multipart/form-data">
<input type="text" name="clearitem" value="<?php echo $r['cart_id'];?>">
<button type="Submit">×</button>
</form>
<?php } ?>
The following is the clearitem.php
code
<?php
if (isset($_POST["clearitem"])) {
$conn = new mysqli("localhost","dbuser","dbpassword","dbname");
$sql = "delete FROM cart where cart_id=?" ;
$stmt = $conn->prepare($sql);
$id=$_POST["clearitem"];
$stmt->bind_param("i", $id);
$stmt->execute();
}
?>
<script>
alert("Done !");
if ('referrer' in document) {
window.location = document.referrer;
/* OR */
//location.replace(document.referrer);
} else {
window.history.back();
}
</script>