Skip to content
Advertisement

“Delete row” button for MySQL in PHP

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>";
   }

Advertisement

Answer

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

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);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement