0

hai i'm trying to make a commenting system using php and mysql (no jquery or ajax) the problem is how to find the id of the post that user comments i used a while loop for that it posts to all the posts so far i'm here.....

//user data is set
if (isset($_POST['comment'])) {
    //variables to post in database
    $comment = $_POST['comment'];
    $com_from = $_SESSION['user'];
    $com_to = $_GET['u'];
    $com_time = date("Y-m-d H:i:s");
    $u = $_GET['u'];

    //query to get the id of the post in the `post` table
    $que = mysql_query("SELECT * FROM posts WHERE `post_to` = '$u'");
    if ($que) {
        //loop through all the posts ad get all ID
        while ($ro = mysql_fetch_array($que)) {
            $pst_id = $ro['post_id'];
            //query inside the while loop for getting the post ID i think here is the problem
            if (!empty($_POST['comment'])) {
                $com_query = mysql_query("INSERT INTO comments SELECT '','$comment',`post_id`,'$com_from','$com_to','$com_time' FROM `posts` WHERE `posts`.`post_id` = $pst_id");
            }
        }
    }
}
flec
  • 2,891
  • 1
  • 22
  • 30

2 Answers2

1

First of all you dont have to go through the loop for quering post table. If you are commenting a specific post pass its ID in html form with hidden type.

// here 1 is id of post
<input type="hidden" name="postid" value="1">

Then you can write insert query like :

if (isset($_POST['comment'])) {
    //variables to post in database
    $comment = $_POST['comment'];
    $com_from = $_SESSION['user'];
    // $com_to is post id and i believe comment table contain field to store post id
    $com_to = $_POST['postid'];
    $com_time = date("Y-m-d H:i:s");
$que = mysql_query("INSERT INTO comments VALUES('$comment','$com_to','$com_from','$com_time')");
}
bsnrijal
  • 494
  • 4
  • 7
0

I have provided the insert query with my limited understanding,

 $pst_id = $_POST['postid']; // from form 

 $com_query = mysql_query("INSERT INTO comments  values ('$comment','$pst_id','$com_from','$com_to','$com_time') ");

I can help you more, if you share your comments table structure.

Note Use mysqli_* functions instead of mysql_* functions (deprecated)

Krish R
  • 22,583
  • 7
  • 50
  • 59