How to delete particular comment from database

Hello All,

Below i my code which enables a user to see all the comments in his profile when logged in. It also has a code which becomes visible to a user’s friend when he visits his profile. Now i want to display an option of delete in front of each comment. When the orginal profile holder or the one who posted it visit the comments section,delete button should appear and in rest case it should not. The only comment needs to be deleted whose delete button is pressed. How should i do it?

$sql="SELECT * FROM comments WHERE for_msg='$u'";
$numrows = mysqli_num_rows($query);
{$show=" You have $numrows Comments";}
else{$show="You dont have any comments yet.";}
if($u != $log_username && $user_ok == true){
    $comment_form  = '<form id="usercommnet" method="post">';
    $comment_form .=   '<h4>Post Your comment for </h4>';
    $comment_form .=   '<input type="text" name="coment" required>';
    $comment_form .=   '<p><input type="submit" value="Submit" name="comet"></p>';
    $comment_form .= '</form>';
else $comment_form="";
if(isset($_POST['comet'])&& $_POST['coment']!="")
$sql="INSERT INTO comments (comment,from_msg,for_msg,datecreated) VALUES('$remov','$u','$log_username',now())";
if($query===TRUE){echo " yahoo";}
<!doctype html>
<meta charset="utf-8">
<title>Untitled Document</title>
.showcomments{width:70%; height:auto; border:#099 1px solid; margin-top:5px; margin-bottom:1px;}


<div><?php echo $show;?></div>
$sql="SELECT * FROM comments WHERE for_msg='$u' ";
$numrows = mysqli_num_rows($query);
if($numrows < 1){
    $filename= "You dont have any comments";
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
    $from_msg = $row["from_msg"];
    $for_msg = $row["for_msg"];
    $comment = $row["comment"];
    $datecreated = $row["datecreated"];
    $code = $row["code"];
    $id = $row["id"];
    $filename="$i &nbsp;&nbsp;&nbsp;&nbsp; $from_msg &nbsp;&nbsp;&nbsp;&nbsp; $comment &nbsp;&nbsp;&nbsp;&nbsp; ";
<div class="showcomments">
<?php echo $filename;?><br></div>
}// Close Main while loop

<?php echo $comment_form;?>


I cannot identify your variable… its hard because it seems that you have given an incomplete code… :slight_smile:

DELETE FROM `comments` WHERE `id` = ?

You did create a primary key on that table to pick out a specific comment yes? If not, you’ve messed up and need to start over - all tables must have a primary key*

Your code is wide open to a potential SQL Injection attack.

$sql="INSERT INTO comments (comment,from_msg,for_msg,datecreated) VALUES('$remov','$u','$log_username',now())";

You need to use prepared statements to elliminate the risk of SQL Injection attacks. The golden rule is to never let ANY user submitted data anywhere near the database without sanitizing it (checking that it matches what you’re expecting to be submitted) and the data once sanitized escaped or prepared statements are used (the preferable option).