首页 > 解决方案 > 如何在不同的页面有来自你的不同评论

问题描述

我正在创建一个包含不同电影的网站,每部电影都有一个特定的 id_movie,我添加了一个评论框,用户可以在其中添加关于电影的评论,但是,我点击的每部电影,它们都显示相同的评论已经进入,我希望每部电影都有自己的评论,如果你能帮助我,我会很高兴。谢谢

评论.php

<body>
 <br />
 <h2 align="center"><p >Add Comment</p></h2>
 <br />
 <div class="container">
  <form method="POST" id="comment_form">
   <div class="form-group">
    <input type="text" name="comment_name" id="comment_name" class="form-control" placeholder="Enter Name" />
   </div>
   <div class="form-group">
    <textarea name="comment_content" id="comment_content" class="form-control" placeholder="Enter Comment" rows="5"></textarea>
   </div>
   <div class="form-group">
    <input type="hidden" name="comment_id" id="comment_id" value="0" />
    <input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
   </div>
  </form>
  <span id="comment_message"></span>
  <br />
  <div id="display_comment"></div>
</div>
</body>

<script>
$(document).ready(function(){

$('#comment_form').on('submit', function(event){
 event.preventDefault();
 var form_data = $(this).serialize();
 $.ajax({
  url:"add_comment.php",
  method:"POST",
  data:form_data,
  dataType:"JSON",
  success:function(data)
  {
   if(data.error != '')
   {
    $('#comment_form')[0].reset();
    $('#comment_message').html(data.error);
    $('#comment_id').val('0');
    load_comment();
   }
  }
 })
});

load_comment();

function load_comment()
{
 $.ajax({
  url:"fetch_comment.php",
  method:"POST",
  success:function(data)
  {
   $('#display_comment').html(data);
  }
 })
}

$(document).on('click', '.reply', function(){
 var comment_id = $(this).attr("id");
 $('#comment_id').val(comment_id);
 $('#comment_name').focus();
});

});
</script>

add_comment.php

<?php

$con = new PDO('mysql:host=localhost;dbname=db_movie', 'root', '');

$error = '';
$comment_name = '';
$comment_content = '';

if(empty($_POST["comment_name"]))
{
 $error .= '<p class="text-danger">Name is required</p>';
}
else
{
 $comment_name = $_POST["comment_name"];
}

if(empty($_POST["comment_content"]))
{
 $error .= '<p class="text-danger">Comment is required</p>';
}
else
{
 $comment_content = $_POST["comment_content"];
}

if($error == '')
{
 $query = "
 INSERT INTO tbl_comment
 (parent_comment_id, comment, comment_sender_name, movie_id)
 VALUES (:parent_comment_id, :comment, :comment_sender_name)
 ";
 $statement = $con->prepare($query);
 $statement->execute(
  array(
   ':parent_comment_id' => $_POST["comment_id"],
   ':comment'    => $comment_content,
   ':comment_sender_name' => $comment_name
  )
 );
 $error = '<label class="text-success">Comment Added</label>';
}

$data = array(
 'error'  => $error
);

echo json_encode($data);

?>

fetch_comment.php

<?php

//fetch_comment.php

$con = new PDO('mysql:host=localhost;dbname=db_movie', 'root', '');

$query = "
SELECT * FROM tbl_comment
WHERE parent_comment_id = '0'
ORDER BY comment_id DESC
";
$statement = $con->prepare($query);

$statement->execute();

$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
 $output .= '
 <div class="panel panel-default">
  <div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
  <div class="panel-body">'.$row["comment"].'</div>
  <div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
 </div>
 ';
 $output .= get_reply_comment($con, $row["comment_id"]);
}

echo $output;

function get_reply_comment($con, $parent_id = 0, $marginleft = 0)
{
 $query = "
 SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
 ";
 $output = '';
 $statement = $con->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $count = $statement->rowCount();
 if($parent_id == 0)
 {
  $marginleft = 0;
 }
 else
 {
  $marginleft = $marginleft + 48;
 }
 if($count > 0)
 {
  foreach($result as $row)
  {
   $output .= '
   <div class="panel panel-default" style="margin-left:'.$marginleft.'px">
    <div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
    <div class="panel-body">'.$row["comment"].'</div>
    <div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
   </div>
   ';
   $output .= get_reply_comment($con, $row["comment_id"], $marginleft);
  }
 }
 return $output;
}

?>

当我点击每部电影时:

<?php include('header.php');
    $qry2=mysqli_query($con,"select * from tbl_movie where movie_id='".$_GET['id']."'");
    $movie=mysqli_fetch_array($qry2);
    ?>
<div class="content">
    <div class="wrap">
        <div class="content-top">
                <div class="section group">
                    <div class="about span_1_of_2">
                        <h3><?php echo $movie['movie_name']; ?></h3>
                            <div class="about-top">
                                <div class="grid images_3_of_2">

                                    <img src="<?php echo $movie['image']; ?>" width="180px" height="280px" alt=""/>
<?php include('ratte.php'); ?>
                                </div>
                                <div class="desc span_3_of_2">
                                    <p class="p-link" style="font-size:15px">Type: <?php echo $movie['type']; ?></p>
                                    <p class="p-link" style="font-size:15px">Price: £<?php echo date($movie['price']); ?></p>
                                    <p style="font-size:15px"><?php echo $movie['desc']; ?></p>
                                    <a href="<?php echo $movie['video_url']; ?>" target="_blank" class="watch_but">Watch Trailer</a>
                                </div>
                                <div class="clear"></div>
                            </div>
                            <?php $s=mysqli_query($con,"select DISTINCT theatre_id from tbl_shows where movie_id='".$movie['movie_id']."'");
                            if(mysqli_num_rows($s))
                            {?>
                            <table class="table table-hover table-bordered text-center">
                            <?php

                                while($shw=mysqli_fetch_array($s))
                                {
                                    $t=mysqli_query($con,"select * from tbl_theatre where id='".$shw['theatre_id']."'");
                                    $theatre=mysqli_fetch_array($t);
                                    ?>
                                    <tr>
                                        <td>
                                            <?php echo $theatre['name'].", ".$theatre['place'];?>
                                        </td>
                                        <td>
                                            <?php $tr=mysqli_query($con,"select * from tbl_shows where movie_id='".$movie['movie_id']."' and theatre_id='".$shw['theatre_id']."'");
                                            while($shh=mysqli_fetch_array($tr))
                                            {
                                                $ttm=mysqli_query($con,"select  * from tbl_show_time where st_id='".$shh['st_id']."'");
                                                $ttme=mysqli_fetch_array($ttm);

                                                ?>

                                                <a href="check_login.php?show=<?php echo $shh['s_id'];?>&movie=<?php echo $shh['movie_id'];?>&theatre=<?php echo $shw['theatre_id'];?>"><button class="btn btn-default"><?php echo date('h:i A',strtotime($ttme['start_time']));?></button></a>

                                                <?php
                                            }
                                            ?>
                                        </td>
                                    </tr>
                                    <?php
                                }
                            ?>
                        </table>
                        <div id='display_comment'></div>
                            <?php
                            }

                            else
                            {
                                ?>
                                <h3>No Show Available</h3>
                                <div id='display_comment'></div>
                                <?php
                            }
                            ?>

                    </div>
                <?php include('related-movies.php');
                ?>
            </div>
                <div class="clear"></div>
            </div>
            <?php include('comments.php'); ?>
    </div>
</div>
<?php include('footer.php'); ?>

标签: javascriptphpmysqlajaxdatabase

解决方案


我会尽力而为,但还有很多内容要讲。

评论.php

//add the target files URL as the form's action
<form method="POST" id="comment_form" action="add_comment.php" > 
 //add movie to the form, that way when we insert the comment we know what its for
 <input type="hidden" name="movie_id" id="movie_id" value="<?php echo $movie_id; ?>" />

//.. in your JS, add the movie id to the fetch comment call
function load_comment()
{
   $.ajax({
      url:"fetch_comment.php",
      method:"POST",
      data: {movie_id : <?php echo $movie_id; ?>},
      dataType: 'json',
      success:function(data){
         //...
  })
 }
 //move this below the function definition
 load_comment();

add_comment.php

    //add movie id here to match what is in the form above
   INSERT INTO tbl_comment
   (parent_comment_id, comment, comment_sender_name, movie_id)
    VALUES (:parent_comment_id, :comment, :comment_sender_name, :movie_id)
   // add ':movie_id' => $_POST['movie_id'] to the array you have there for
  // $statement->execute([ ....]). The arrays below go the same way 
   //add those to $statement->execute() for there respective DB calls,

您在插入的 FIELDS 部分中有电影,但没有 VALUES,这可能是 SQL 语法错误。您可能没有看到实际错误,因为这是使用 AJAX 调用的,因此它只会在客户端中断。您可以查看浏览器调试窗口 > 网络 [XHR] 请求并查看响应。您可能会在那里找到它,或者您可能只是从服务器收到 500 错误。


fetch_comment.php

    //add movie id here to match what is in the AJAX fetch comment call
   SELECT * FROM tbl_comment
   WHERE parent_comment_id = :parent_comment_id  AND movie_id = :movie_id 
    ORDER BY comment_id DESC
    //for execute add 
     ['parent_comment_id'=>0, 'movie_id'=>$_POST['movie_id']]

重要的是正确准备此查询

   $query = "
 SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
 ";

所以它应该是这样的:

$query = "SELECT * FROM tbl_comment WHERE parent_comment_id = :parent_id";
//then add this to execute ['parent_id' => $parent_id]

mainpage.php(不确定这个名称)

在您使用的最后一个未命名的代码块中,mysqli但在您使用PDO的之上,最好使用其中一个或另一个,我个人更喜欢 PDO,它只是在 API 方面更好。您也没有准备这些(因此将这些转换为 PDO)。两者都使用只会给您的应用程序增加不必要的复杂性(我认为其中有 2 篇论文):

$qry2=mysqli_query($con,"select * from tbl_movie where movie_id='".$_GET['id']."'");
$movie=mysqli_fetch_array($qry2);

看起来您将其包含在comments.php最后一页中<?php include('comments.php'); ?>所以我要做的是查询在上面我说要修复的位置:

   require_once `db.php`; //- create a separate file to do the DB connection for you
  //then you can add that to the top of all the pages you need the DB for

   include 'header.php'; //no need for the ( ) for any of the include* or require* calls.
   /*
   require will issue an error if the included file is not found
   include will fail silently, for things that are required for your 
   page to work and not produce errors use require (like the DB)
   for things you only ever include once, also like the DB stuff use *_once
   then no matter how many *_once calls are stacked from including
   the other page you don't have to worry about it.

    as above those simple rules give us require_once for the DB.
    the other pages I am not sure which would be best.
   */

   //localize the movie ID - change any use of `$_GET['id']
  $movie_id = isset($_GET['id']) ? $movie_id : false;

  if(!$movie_id){
      //do something if someone goes to this page with no ?id= in the URL
      //you could redirect the page
      //you could have a default movie id etc...
  } 

  $statement = $con->prepare('select * from tbl_movie where movie_id=:movie_id');
  $statement->execute(['movie_id' => $movie_id]);
  $movie = $statement->fetch();

  //dont forget to fix the other DB call and remove the MySqli stuff.

上面我建议对数据库使用单个文件,在你的情况下它可以很简单,

数据库.php

    <?php $con = new PDO('mysql:host=localhost;dbname=db_movie', 'root', '');

这实际上就是您所需要的,在您使用数据库的每个页面的最顶部,只需添加此文件

    require_once 'db.php';

这样,如果您需要更改密码或类似的东西,您可以去一个以易于记忆的方式命名的地方并更改它。现在情况如何,您将不得不挖掘所有代码来更改它。在该页面中,您包含一个名为的文件header.php,从您的 MySQLi 代码看来,它可能包含一些连接内容。我也会在那里删除任何 MySQLi 的东西。您希望将 DB 文件分开,因为您可能需要将其包含在 AJAX 后端部分中,并且 header.php 的任何输出都会让您感到困惑。

夏天的

我上面展示的是一个简单的例子,说明你需要做什么,在那个 AJAX 调用中这可能不是你需要做的全部,这些对我来说只是显而易见的事情。

您不必担心子评论的电影 ID,因为他们从父评论继承它,如果它的 ID 错误,它就不会存在(在页面上)。在您当前的设置中,我仍会将其保存为数据的一部分。如果您知道父母(您必须知道),那么您就不需要它来获得孩子的评论。我没有将它添加到看起来像是用于儿童评论的一件事中。您可以添加它,但正如我上面所说,它并不是真正需要的。

确实,问题很广泛,为什么我的代码不能正常工作。我付出努力的唯一原因是您还努力提供相对最少的组织良好的代码。

非常感谢你的帮忙。

我要提出的最后一个建议是清理一些 SQL 中的额外行返回,并更好地格式化 TAB。但这只是一个可读性问题,我对格式化我的代码非常挑剔,其中一些可能与在 SO 上创建一个问题有关,因为它需要一些时间来使用他们使用的降价。

希望对你有帮助!

更新

感谢您的回答,我真的不知道我应该在这里发布什么,我不应该发布什么,我不明白的是:我有一个 tbl_comment 存储用户的所有评论,这个表包括 movie_id,我还有另一个 tbl_movie将movie_id作为主键,我如何将电影_id与tbl_comment链接起来,以便为特定的movie_id存储每个评论

我将尝试通过一个示例来解释您的应用程序的流程。为了这个例子,假设电影 id 是12,我们的主页是www.example.com/movies?id=12

插入评论

  1. 用户转到一个网址?id=12
    • 之后的所有内容都?称为查询字符串
    • PHP 知道获取查询字符串并填充晚餐全局$_GET
    • 所以在主页上你的电影ID现在是$_GET['id']
  2. 我们通过一些基本检查将其本地化(创建一个局部变量)在页面顶部。$movie_id = isset($_GET['id']) ? $movie_id : false;
    • 如果设置了电影 ID,则将?id=12其放入$movie_id
    • 如果不是www.example.com/movies,则设置$movie_id为 false
    • 如果有人在没有该设置的情况下进入页面,这可以避免一些错误
  3. 在页面底部包含此文件<?php include('comments.php'); ?>,将其视为将代码粘贴到此位置
  4. In comments.php,当它包含在上面时运行,

    • 如果有人插入新评论(提交表单),我们已经$movie_id用这一行将其添加到表单中
    • <input type="hidden" name="movie_id" id="movie_id" value="<?php echo $movie_id; ?>" />. - 所以现在当表单提交时add_comment.php,您需要将表单的操作放入其中。
    • <form method="POST" id="comment_form" action="add_comment.php" >
    • 它将包含$_POST['movie_id']该页面上的 id。The$_POST['movie_id']基本相同,$_GET['id']但表格method告诉我们它的post而不是get. 通常Get用于检索资源,Post用于修改它们。
    • 当 PHP 运行上面的 HTML 时,它会<?php echo $movie_id; ?>用它的值替换 ,12所以你会得到这个
    • <input type="hidden" name="movie_id" id="movie_id" value="12" />
  5. 现在在add_comment.php(表单操作将我们带到哪里),我们可以将其$_POST['movie_id']添加到您的 SQL 中,用于在 #4 中插入表单中的评论。进入数据库。

    • INSERT INTO tbl_comment (parent_comment_id, comment, comment_sender_name, movie_id) VALUES (:parent_comment_id, :comment, :comment_sender_name, :movie_id)
    • :movie_id由于这是一个准备好的语句,我们在 SQL 查询中有占位符。在 PDO 中,我们可以将其提供给 PDOStatment 对象($statement),您可以$statment=$conn->prepare($sql)通过调用它的execute方法或$statement->execute([..other stuff here..., 'movie_id'=>$_POST['movie_id']]).
    • PHP 完成后运行的查询如下所示
    • INSERT INTO tbl_comment (parent_comment_id, comment, comment_sender_name, movie_id) VALUES (0, 'foo', 'ArtisticPhoenix', 12)<--看看我在那里做了什么。

所以你看到我们从原始 URL 请求中获取了值,将它添加到我们的表单中,然后我们等待用户操作提交带有嵌入电影 ID 的表单。当表单提交时,它调用我们的添加评论页面,我们将其从已发布数据中取出,并将其与该评论的其余表单数据一起输入数据库。

除了我们使用 AJAX 提交数据的那些之外,其他的完全一样,所以我们只是将它添加到 AJAX 调用中而不是表单。我会给你一个如何执行的例子。

显示评论

这与上面的 #4 相同

  1. comments.php你调用load_comment();“之后”定义函数时,因为它不存在告诉你这样做,所以你不能在之前调用它。
    • 这将运行您的 AJAX 请求$.ajax,就本示例而言,将其视为一种制作表单的奇特方式。url就是形式action就是method方法。data是表单数据,在这种dataType情况下是编码类型JSON或 Javascript Object Notation。这是一种说结构化数据的奇特方式,因为在 PHP 中它基本上是一个数组(或具有嵌套元素的数据)。
  2. url ( action) 指向我们fetch_comment.php,所以当它运行时,我们data: {movie_id : <?php echo $movie_id; ?>},data: {movie_id : 12},其发送回 PHP 将其视为的服务器$_POST['movie_id']
    • 与插入类似,我们在提取父评论的 SQL 查询中使用该 ID
    • SELECT * FROM tbl_comment WHERE parent_comment_id = :parent_comment_id AND movie_id = :movie_id ORDER BY comment_id DESC
    • 这表示“从表 tbl_comment 中选择所有列,其中 parent_comment_id 为 0,电影 ID 为 12”因此它只会返回也是父母的电影 12 的评论。
    • 在您的代码中,您刚刚$statement->execute();但是您将parent_comment_id硬编码为0. 在我们需要添加“movie_id一旦我们做了”之前,这是最好的,让它成为准备好的语句的一部分更有意义,这样它读起来更好。但就像插入一样,现在我们用占位符代替值,因此我们需要获取该数据并将其添加execute到此查询中。
    • 因此,$statement->execute();$statement->execute(['parent_comment_id'=>0, 'movie_id' => $_POST['movie_id']]); PHP 完成它时$statement->execute(['parent_comment_id'=>0, 'movie_id' => 12]);,数据库知道使用键来匹配占位符并完成我们的查询。
    • SELECT * FROM tbl_comment WHERE parent_comment_id = 0 AND movie_id = 12 ORDER BY comment_id DESC
    • 然后我们获取结果并将它们发送回successAJAX 的处理程序,echo在这种情况下,使用这一行将其添加到页面中$('#display_comment').html(data);

所以总而言之

你的代码:

load_comment();

function load_comment()
{
 $.ajax({
  url:"fetch_comment.php",
  method:"POST",
  success:function(data)
  {
   $('#display_comment').html(data);
  }
 })
}

正确的代码(我所说的):

//.. in your JS, add the movie id to the fetch comment call
function load_comment()
{
   $.ajax({
      url:"fetch_comment.php",
      method:"POST",
      data: {movie_id : <?php echo $movie_id; ?>},
      dataType: 'json',
      success:function(data){
         //...
  })
 }
 load_comment();

你需要做什么

//$movie_id = $_GET['id'] in the main page that included this file.. #2 above
function load_comment()
{
 $.ajax({
  url:"fetch_comment.php",
  method:"POST",
  data: {movie_id : <?php echo $movie_id; ?>}, 
  dataType: 'json',
  success:function(data)
  {
   $('#display_comment').html(data);
  }
 });
}
 load_comment();

当 PHP 完成上述代码时,它会将其发送给客户端(使用12我们的示例)

//$movie_id = $_GET['id'] in the main page that included this file.. #2 above
function load_comment()
{
 $.ajax({
  url:"fetch_comment.php",
  method:"POST",
  data: {movie_id : 12},  //PHP takes the value of  $movie_id and puts it here
  dataType: 'json',
  success:function(data)
  {
   $('#display_comment').html(data);
  }
 });
}
load_comment();

以上是浏览器中实际运行的内容

这就是它的要点。正如我所说,了解它的工作原理对您更有益。当然我可以发布完整的代码,但我无法测试它,无法知道这是否是所有错误。如果您了解它的工作原理,您将更有能力自己应对这些挑战。我宁愿花 3 到 4 倍的精力教你它是如何工作的,然后发布一些你不知道它是如何工作的代码。

希望一切都有意义。


推荐阅读