0

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>&nbsp;</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?

Sal Vadala
  • 17
  • 3
  • 1
    `` is missing its `name="id"` attribute. But there's a much more serious problem in SQL injection here. It is trivially easy to delete all records in your database. It is very important to review [How can I prevent SQL injection in PHP](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Michael Berkowski Oct 09 '15 at 17:40
  • 2
    At a minimum, you must call `mysql_real_escape_string()` on `$_POST['id']`, but the `mysql_*()` functions are deprecated and not suitable for use in new code. – Michael Berkowski Oct 09 '15 at 17:40

2 Answers2

1

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']."' /> 
0

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.

chris85
  • 23,846
  • 7
  • 34
  • 51