Reputation: 69
I need some advice on how to dynamically target the rows I wish to delete as currently I am manually having to alter my php script to delete rows but am a little stuck on where to go next.
so here is my index of items:
<?php
$result = mysqli_query($con,"SELECT * FROM items");
while($row = mysqli_fetch_array($result)) {
echo $row['added'] . $row['content'] . $row['id'];
echo "<br>";
echo "Mark as complete";
echo "<br>";
echo "<a href='delete.php'>Delete Item</a>";
echo "<br>";
echo "<a href='update.php'>Edit Item</a>";
echo "<br>";
echo "<br>";
}
mysqli_close($con);
?>
If I click on delete item it will only delete the one I have specified it to in my php here:
mysqli_query($con,"DELETE FROM items WHERE id='14'");
mysqli_close($con);
Now I need to know how to tell the button to delete the item that the link is associated to as you can I have manually entered 14 so that will delete that one. But I need some instruction or advice on how to delete the row or item id of that row in the database.
My initial thoughts are I am going to need to pass some information about this row perhaps using $_GET?
Upvotes: 0
Views: 1358
Reputation: 1299
Secure solution:
$id = $con->real_escape_string($_GET['id']);
$sth = $con->prepare("DELETE FROM items WHERE id=?");
$sth->bindParam(1, $id);
$sth->execute();
Upvotes: 0
Reputation: 1452
You need to pass the ID of the item to be deleted in the URL of delete.php
. First add the ID to the url:
echo '<a href="delete.php?id='. $row['id'] .'">Delete Item</a>';
Then, in delete.php
you need to use $_GET
to get the paramater from the URL, and insert that into the delete query:
$id =$_GET['id'];
$result = mysqli_query("DELETE FROM items WHERE id='$id'");
However, you need to be aware that anyone can then come along, type in a URL in the format 'delete.php?id=' and it will delete that item. You should:
Upvotes: 2
Reputation: 3205
Index of items page:
echo "<a href='delete.php?id=" . $row['id'] . "'>Delete Item</a>";
Delete file:
$id = $con->real_escape_string($_GET['id']); // preventing sql injections
$con->query("DELETE FROM items WHERE id='$id'");
Upvotes: 1