0

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?

3 Answers 3

2

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:

Sign up to request clarification or add additional context in comments.

Comments

1

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'");

4 Comments

Glad I could help, remember to mark the question as complete :)
real_escape_string is not the best solution to prevent SQL injections
I am only learning at the moment so I am just trying to understand how and why things work so security is no issue for me at the moment.
Security should always be part of your learning. It is fundamental.
0

Secure solution:

    $id = $con->real_escape_string($_GET['id']);
    $sth = $con->prepare("DELETE FROM items WHERE id=?");
    $sth->bindParam(1, $id);
    $sth->execute();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.