I'm trying to create a form in PHP that will delete a row in a MySQL database based on the ID of that row. For some reason the form doesn't seem to be passing the ID so it doesn't know what row to delete. This is my form:
<?php
//connect to the database//
include 'mysqlconnect.php';
?>
<?php $result = mysql_query("SELECT * FROM images"); ?>
<?php
echo "<table border='1'>
<tr>
<th>Image ID</th>
<th>Image</th>
<th>Description</th>
<th> </th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td><img src='" . $row['image'] . "' width='300px' /></td>";
echo "<td>" . $row['description'] . "</td>";
echo "<td>
<form method='post' action='deleted.php'>
<input type='hidden' value='".$row['id']."' />
<input name='delete' type='submit' id='delete' value='Delete'>
</form>
</td>";
echo "</tr>";
}
echo "</table>"; // Close table
?>
The form data comes in, including the id. The form goes to deleted.php and here is the code on that page:
<?php
//connect to the database//
include 'mysqlconnect.php';
?>
<?php
$id = $_POST['id'];
$query = "DELETE FROM images WHERE id = '".$id."'";
if(mysql_query($query)){
echo "deleted image ". $id;
//test to see if id is coming
echo $id;
} else{
echo "fail";
}
?>
This returns a success but the image is not deleted and the id does not come in. Any ideas?
You haven't named the input field that contains the id.
This:
<input type='hidden' value='".$row['id']."' />
Needs to become this:
<input type='hidden' name='id' value='".$row['id']."' />
You are not sending id
to PHP through the form. Just set the name attribute of your hidden input field to id
and it will make send to the PHP.
<form method='post' action='deleted.php'>
<input type='hidden' name='id' value='".$row['id']."' />
<input name='delete' type='submit' id='delete' value='Delete'>
</form>
Don't use mysql_
fuctions they are deprecated in higher versions of PHP. Use mysqli_
or PDO
instead of mysql_
.
Happy coding.