I am pulling a list of products from my MYSQL database and using a delete button against each product in case the operator wants to delete the product.
The problem is that every time I hit the delete button on any product in the list, the first element gets deleted.
What's wrong with my code below ?
Products
page:
<?php
$link=mysqli_connect("localhost","root","","smartcart");
$prod="select * from products";
$rw=mysqli_query($link,$prod) or die(mysqli_errno()."in query $prod");
$count=1;
while($row=mysqli_fetch_assoc($rw))
{
echo "<tr>";
echo "<td>".$count."</td>";
echo "<td>".$row['prod_id']."</td>";
echo "<td>".$row['prod_name']."</td>";
echo "<td>".$row['prod_price']."</td>";
echo "<td><form action='delete_prod.php' id='delete' method='get'>";
echo "<input type='hidden' name='prod_id' value='".$row['prod_id']."' />";
echo "<button type='submit' form = 'delete' class='btn btn-default' name='delete'>Delete</button>";
echo "</form></td>";
$count=$count+1;
}
mysqli_free_result($rw);
?>
delete_prod.php
:
<?php
if(isset($_GET['delete']))
{
include "connection.php";
$prod_id=$_REQUEST['prod_id'];
$del="delete from products where prod_id=$prod_id";
if (mysqli_query($link,$del))
{
echo "Successfully deleted";
unset($_POST['delete']);
}
else
{
echo "Delete operation Failed";
}
header('location:show_db.php');
}
?>
I think I am terribly missing some simple point, but am unable to get what is it.
Check
prod_id
is auto incrementing properly or not in your table. Another thing is as your form is in loop the id for all forms will be duplicated. So each time it is submitting first form, thats why only first product is deleted from your record.for delete action code in delete_prod.php
try this...
Most likely because you setup the
id="delete"
. Usually id attribute values are not duplicated.The submit button gets the first ID and thus getting the first hidden input.
Alternatively, you could devise your button like this and serve as your marker:
No need to print each form!. Just wrap it with the table:
Then in PHP processing: