kenny kenny - 2 years ago 69
SQL Question

Delete The Selected ID from Mysqli

I have a comment section on my index.php page. (like I have displayed here) I have a delete link that sends you to the delete page. I want to be able to delete that specific ID when it is clicked.

<div class='commentnest'>
<p id='id'> ".$row['id']."</p>
<p id='user'> ".$row['user'].":</p>
<p id='comment'>".$row['usercomment']." </p>
<p id='time'>".$row['timestamp']."</p>
<a href='delete.php?=".$row['id']."'>Delete</a>

delete.php page

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
$sql = "DELETE FROM commenttable WHERE id=id";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);

every time I send a specific comment there, it deletes all the comments. I know it's because I'm not stating which ID to select, but i'm having a hard time figuring that out.

Thanks for any help!

Answer Source

All records are deleted because id=id will be always true unless id is NULL. You need to properly pass it from your HTML:

<a href='delete.php?id=".$row['id']."'>Delete</a>

and then properly use it in the query:

$sql = "DELETE FROM commenttable WHERE 
  id='".mysqli_escape_string($conn,$_REQUEST["id"])."'" ;

if the id is always an integer, you can write simpler:

$sql = "DELETE FROM commenttable WHERE 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download