Hello All,
I have a table that stores comments for a user posted to him/her by friends.
I am displaying them by using the below code. I am also displaying a delete button in front of each comment. But that delete button is not working. Please see whats the error here. Only that comment needs to be deleted whose delete button is pressed.
<?php
include_once("php_includes/check_login_status.php");
if($user_ok==FALSE)
{
header("location: http://www.mysite.com");
exit();
}
$sql="SELECT * FROM comments WHERE for_msg='$log_username'";
$query=mysqli_query($db_conx,$sql);
$numrows = mysqli_num_rows($query);
?>
<?php
if(isset($_POST['$id']))
$id=preg_replace('#[0-9]#', '', $_POST['$id']);
$sql= "Delete from comments WHERE for_msg='$log_username' AND id='$id'";
$query=mysqli_query($db_conx,$sql);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<div>
<?php echo "you have $numrows comments;"?><br/>
<?php
include_once("php_includes/db_conx.php");
$sql="SELECT * FROM comments WHERE for_msg='sultan' ";
$query=mysqli_query($db_conx,$sql);
$numrows = mysqli_num_rows($query);
if($numrows < 1){
$filename= "You dont have any comments";
exit();
}
else
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$from_msg = $row["from_msg"];
$for_msg = $row["for_msg"];
$comment = $row["comment"];
$datecreated = $row["datecreated"];
$id = $row["id"];
$filename="$id $from_msg $comment ";
$avatar_form = '<form id="avatar_form" enctype="multipart/form-data" method="post">';
$avatar_form .= '<p><input type="submit" name="$id" value="Delete"></p>';
$avatar_form .= '</form>';
?>
<?php echo $filename;?><?php echo $avatar_form; ?><br>
<?php
}// Close Main while loop
?>
</div>
</body>
</html>
Try this instead. I only changed a few things … mainly your if (islet()) and the delete form. Your main issue was populating the form incorrectly and checking it incorrectly in the “if” section. The other changes are just for readability sake.
The action tells the browser where to submit the form. If you’re on comments.php, and comments.php is what will be deleting that entry, then use that for the action:
Or if the page is named something else, change it to that name.
You also don’t have any error checking with your SQL. Add an “echo $sql;” right after you set the $sql variable to make sure the variables are correct. Check the MySQLi docs to print out any DB errors you may be getting.