I have a table that becomes populated with data from a MySQL database, and each row receives its own delete button. I would like to have the option to delete each row separately with a delete button that deletes the corresponding row in the database. How would I go about doing so? Here's the part of the code that I have to far, which does not seem to work whatsoever.
if(isset($_POST['id'])) {
$id = $_POST['id'];
$delete = mysql_query($conn,"DELETE FROM mods WHERE id = '$id'");
}
Unimportant code omitted.
Table/Form Creation:
echo "<td><form action=\"\" method=\"post\"></td>";
echo "<tr class='modlist'>";
echo "<td>".$row['id']."</td>";
echo "<td><div class=\"edit\" id=\"div_1\">".$row['title']."</div></td>";
echo "<td><div class=\"edit\" id=\"div_2\"><a href=".$row['mod_url'].">".$row['mod_url']."</a></div></td>";
echo "<td><div class=\"edit\" id=\"div_3\">".$row['developer']."</div></td>";
echo "<td><div class=\"edit\" id=\"div_4\">".$row['type']."</div></td>";
echo "<td><div class=\"edit\" id=\"div_5\">".$v162."$nbsp".$v164."$nbsp".$v172."</div></td>";
echo "<td><div class=\"edit\" id=\"div_6\">".$row['title'].",$nbsp".$row['developer']."</div></td>";
echo "<td><div id=\"save\"><input type=\"submit\" name=\"save\" value=\"Save\"></div></td>";
echo "<td><div id=\"delete\"><input type=\"submit\" name=\"delete\" value=\"Delete\"></div></td>";
echo "</tr>";
echo "</form>";
}
You have the parameters for mysql_query()
backwards. First pass the query, then pass the $conn.
$delete = mysql_query("DELETE FROM mods WHERE id = '$id'", $conn);
But beware you now have an SQL injection problem! Sanitize $id before you use it!
$id = mysql_real_escape_string($id);
And consider using mysqli
or PDO
(and use parameterized queries), as mysql_*
are deprecated!
Form action needs to have a control with the name 'id', otherwise $_POST will not get any id.
You can do it like <input type="hidden" name="id" value=".$row['id']." />
<input type="hidden" name="id" value=".$row['id']." />
Also, I suggest you have a look at How can I prevent SQL injection in PHP? as your form, by the code you displayed, looks completely vulnerable.
UPDATE
You also have to fix your $delete
query like nl-x mentioned:
$delete = mysql_query("DELETE FROM mods WHERE id = '$id'", $conn);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.