Yohan Blake Yohan Blake - 2 years ago 95
SQL Question

Add a delete button to a table populated from a database

I have a table which I populate from a mysql db. I want to add a delete button to each of the rows in the table, and when the button is clicked, I want to remove that line from the db table. I am using an array to update any changes made to the table. How can I use that array to delete a specific row too?

<tr><th>Category ID</th><th>Description</th><th>Valid</th><th></th></tr>
$query=mysqli_query($link,"SELECT * FROM cd_categories");
while($row = mysqli_fetch_array($query)){
$catid = $row['Catg_Id'];
$des = $row['Description'];
$datep = $row['Date_Posted'];
$postedb = $row['Posted_By'];
$valid = $row['Valid_YN'];

<tr><td><input type="text" name="data[<?php echo $catid; ?>][catid]" value="<?php echo $catid; ?>" ></td>
<td><input type="text" name="data[<?php echo $catid; ?>][des]" value="<?php echo $des; ?>" ></td>
<td><input type="button" name="data[<?php echo $catid; ?>][delete]" value="Delete" ></td>
<?php } ?>
<input type="submit" name="update" value="Save Changes" >

Answer Source

To remove a row from database you need to use a DELETE statement with a primary key, which you need to pass from this while loop.

Make a link inside while loop: [Demo]

<a href='delete.php?id=your_id'>Delete</a> 

Now in your delete page, you need to capture or store the id using $_GET and using the DELETE Statement you can simply delete row from database.

DELETE FROM table_name WHERE primary_key=your_get_value;

Note: In your delete page just make a query for delete the row also make some security.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download