评论如果我在相关帖子中添加评论它是评论的两倍

时间:2018-01-05 14:43:23

标签: php mysql

任何时候我通过点击提交1条评论它会在数据库上加倍,不知道为什么。我有post_comment_count列,每当我点击提交时我都会加上+1。我希望它只添加1而不是2。

例如 我有一个帖子它有一个评论计数器示例在相关帖子上有0条评论 当我提交一条评论时 实际上它提交了1条评论,但它增加了两倍的价值:/

<?php   

       if(isset($_POST['create_comment'])){

           $the_post_id = $_GET['p_id'];

                    $comment_author =$_POST['comment_author'];
                        $comment_email =$_POST['comment_email'];
                        $comment_content = $_POST['comment_content'];


           $query  = "INSERT INTO comments (comment_post_id, comment_author, comment_email, comment_content, comment_status, comment_date)";
           $query .= "VALUES ($the_post_id, '{$comment_author}', '{$comment_email}', '{$comment_content}', 'unapproved', now())";

             $query = "UPDATE posts SET post_comment_count = post_comment_count + 1 ";
                 $query .= "WHERE post_id = $the_post_id ";
                 $update_comment_count = mysqli_query($connection,$query);

                    }           


                 $create_comment_query= mysqli_query($connection,$query);

                 if(!$create_comment_query){
                     die('Query failed' . mysqli_error($connection));
                 }




     ?>

如果我这样做

<?php   

   if(isset($_POST['create_comment'])){

       $the_post_id = $_GET['p_id'];

                $comment_author =$_POST['comment_author'];
                    $comment_email =$_POST['comment_email'];
                    $comment_content = $_POST['comment_content'];


       $query  = "INSERT INTO comments (comment_post_id, comment_author, comment_email, comment_content, comment_status, comment_date)";
       $query .= "VALUES ($the_post_id, '{$comment_author}', '{$comment_email}', '{$comment_content}', 'unapproved', now())";



                }           


             $create_comment_query= mysqli_query($connection,$query);

             if(!$create_comment_query){
                 die('Query failed' . mysqli_error($connection));
             }

                     $query = "UPDATE posts SET post_comment_count = post_comment_count + 1 ";
             $query .= "WHERE post_id = $the_post_id ";
             $update_comment_count = mysqli_query($connection,$query);


 ?>

它的功能相同,但页面刷新时不是通过点击。

1 个答案:

答案 0 :(得分:0)

正如@Funk在评论中指出的那样,你正在覆盖你的查询,这肯定会在数据库上执行意外的工作。

$query  = "INSERT INTO comments (comment_post_id, comment_author, comment_email, comment_content, comment_status, comment_date)";
           $query .= "VALUES ($the_post_id, '{$comment_author}', '{$comment_email}', '{$comment_content}', 'unapproved', now())";

然后,立即执行

$create_comment_query= mysqli_query($connection,$query);

然后,

$query = "UPDATE posts SET post_comment_count = post_comment_count + 1 WHERE post_id = $the_post_id ";
$update_comment_count = mysqli_query($connection,$query);