I have an image upload form and it works fine.
But underneath that same form I want some sort of image listing where I can delete specific image by clicking on its X button.
I wrote the code and it works but it always deletes the first image on the list, no matter which X I click on.
<form method="post">
<ul>
<?php
$host = "127.0.0.1"; //database location
$user = ""; //database username
$pass = ""; //database password
$db_name = ""; //database name
if(!$link = mysql_connect($host, $user, $pass)) {
echo "<p>error: ".mysql_error()."</p>";
} else {
mysql_select_db($db_name);
}
$selectAll = "SELECT image_name FROM home_images";
$doIt = mysql_query($selectAll);
// if(isset($_POST['delete'])) {
// mysql_query("DELETE FROM home_images WHERE image_name = ");
// }
?>
<?php while($result = mysql_fetch_array($doIt)) : ?>
<li style="display:inline; margin-right:10px">
<img src="<?php bloginfo('url') ?>/wp-content/uploads/<?php echo $result[0]; ?>" height=50 width=60 />
<input type="hidden" value="<?php echo $result[0]; ?>" name="imagename" />
<input type="submit" value="X" name="delete" />
</li>
<?php endwhile; ?>
<?php
if(isset($_POST['delete'])) {
$imagename = $_POST['imagename'];
$deleter = "DELETE FROM home_images WHERE image_name = '$imagename'";
if(mysql_query($deleter)) {
echo "Successful!";
echo $imagename;
} else {
echo mysql_error();
}
}
?>
</ul>
</form>
What am I doing wrong here?
The problem is that you put everything inside the same form. When the form has multiple fields with the same name it sends only one of them.
Make a separate form for each delete button:
By the way, you have a huge security issue with the SQL query. Always sanitize incoming data.