【问题标题】:how to have different comments from you in different pages如何在不同的页面有来自你的不同评论
【发布时间】:2019-08-03 14:08:36
【问题描述】:

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

cmets.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'); ?>

【问题讨论】:

  • 您的 INSERT 查询中缺少 movie_id
  • 在获取 cmets 的“AJAX”调用中,$.ajax({url:"fetch_comment.php", 您需要将电影 ID 传递回 PHP,然后在后端将该 ID 添加到 SQL 中以获取 cmets。 SELECT * FROM tbl_comment WHERE parent_comment_id = '0' AND movie_id=? ORDER BY comment_id DESC 对于 AJAX 添加 dataType:"json" 然后对于 data: 类似 {movie_id : &lt;?php echo $movie_id; ?&gt;}
  • 基本上,您必须在构建页面时获取您拥有的电影 ID,并将其提供给您的调用以获取 cmets,然后它有点像掉头,然后返回到服务器你在哪里得到cmets。哦,差点忘了,在上面获取通信的函数中使用我的示例,您将使用$_POST['movie_id'] 确保使用准备好的 SQL 语句以确保安全,这样人们就无法破解您的 SQL。现在是晚餐,但我可以在 30 分钟左右发布正确的答案。
  • 我试过这个东西(AND movie_id=?),但它说这个错误:PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: no parameters in line 15
  • 我在编码方面不是那么专业,我真的不知道该怎么做,如果你有想法可以请你更新我的代码,我会感谢你的帮助

标签: javascript php mysql ajax database


【解决方案1】:

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

cmets.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]

ma​​inpage.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 包含在最后一页&lt;?php include('comments.php'); ?&gt; 中,所以我要做的是上面我说要修复的查询:

   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.

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

db.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 错误,则不会存在(在页面上)。在您当前的设置中,我仍会将其保存为数据的一部分。如果您知道父母(您必须知道),那么您就不需要它来获得子 cmets。我没有将它添加到看起来像是用于儿童评论的一件事中。您可以添加它,但正如我上面所说,它并不是真正需要的。

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

所以谢谢你。

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

希望对你有帮助!

更新

感谢您的回答,我真的不知道我应该在这里发布什么以及我不应该发布什么,我不明白的是:我有一个 tbl_comment 存储来自用户的所有 cmets,并且该表包括 movie_id,我有另一个以 movie_id 作为主键的 tbl_movie,我如何将电影 _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. 在页面底部包含此文件&lt;?php include('comments.php'); ?&gt; 将其视为将代码粘贴到此位置
  4. comments.php 中,当它包含在上面时运行,

    • 如果有人插入新评论(提交表单),我们已经在表单中添加了相同的 $movie_id
    • &lt;input type="hidden" name="movie_id" id="movie_id" value="&lt;?php echo $movie_id; ?&gt;" /&gt;。 - 所以现在当表单提交到add_comment.php 时,您需要将其放入表单的操作中。
    • &lt;form method="POST" id="comment_form" action="add_comment.php" &gt;
    • 它将在该页面上包含$_POST['movie_id'] 的ID。 $_POST['movie_id']$_GET['id'] 基本相同,但method 的形式告诉我们它的post 而不是get。通常Get 用于检索资源,Post 用于修改它们。
    • 当 PHP 运行上面的 HTML 时,它会将 &lt;?php echo $movie_id; ?&gt; 替换为 12 的值,因此您会得到这个
    • &lt;input type="hidden" name="movie_id" id="movie_id" value="12" /&gt;
  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)
    • 由于这是一个准备好的语句,我们在 SQL 查询中有占位符 :movie_id。在 PDO 中,我们可以将它提供给 PDOStatment 对象 ($statement),您可以通过调用它的 execute 方法或 $statement-&gt;execute([..other stuff here..., 'movie_id'=&gt;$_POST['movie_id']])$statment=$conn-&gt;prepare($sql) 返回。
    • 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,就本示例而言,将其视为一种创建表单的奇特方式。 urlaction 的形式method 是很好的方法。 data 是表单数据,dataType 是本例中的编码类型 JSON 或 Javascript Object Notation。这是一种说结构化数据的奇特方式,因为在 PHP 中它基本上是一个数组(或具有嵌套元素的数据)。
  2. url (action) 将我们指向fetch_comment.php,因此当它运行时,我们的data: {movie_id : &lt;?php echo $movie_id; ?&gt;}, 变为data: {movie_id : 12},,它被发送回服务器,PHP 将其视为$_POST['movie_id']
    • 与插入类似,我们在提取父 cmets 的 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 的 cmets。
    • 在您的代码中,您只有$statement-&gt;execute();,但您将parent_comment_id 硬编码为0。在我们需要添加 movie_id 之前,这已经很好了。但就像插入一样,现在我们用占位符代替值,因此我们需要获取该数据并将其添加到 execute 以进行此查询。
    • 所以$statement-&gt;execute(); 变为$statement-&gt;execute(['parent_comment_id'=&gt;0, 'movie_id' =&gt; $_POST['movie_id']]); 或者当PHP 完成$statement-&gt;execute(['parent_comment_id'=&gt;0, 'movie_id' =&gt; 12]); 时,数据库知道使用键来匹配占位符并完成我们的查询。
    • SELECT * FROM tbl_comment WHERE parent_comment_id = 0 AND movie_id = 12 ORDER BY comment_id DESC
    • 然后我们获取结果并将它们发送回 success 处理程序以使用 echo 进行 AJAX,在这种情况下将其添加到带有此行 $('#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 倍的精力教你它是如何工作的,然后发布一些你不知道它是如何工作的代码。

希望这一切都有意义。

【讨论】:

  • 非常感谢您的宝贵时间,我没有收到任何错误,但同时所有消息都消失了
  • 我应该在哪里添加这个? >> ['parent_comment_id'=>0, 'movie_id'=>$_POST['movie_id']]
  • 数组需要像 INSERT 一样进入-&gt;execute([array]) 部分。发布所有代码似乎很啰嗦。另外,我喜欢教书,而不是做事。所以留下一些事情让你去做是件好事。
  • @beg - 它是一个 sql 错误,但是因为您通过 AJAX 调用它,所以您看到它的唯一方法是查看 f12 浏览器调试窗口中的网络面板。我添加了一些东西,并把它美化了一点。
  • 你在用我觉得专业编码员的词,我对编程很陌生,我正在尝试做这个 cmets 功能,如果有任何非常简单的方法我可以做到这一点可以工作,请告诉我
猜你喜欢
  • 1970-01-01
  • 2013-08-28
  • 1970-01-01
  • 1970-01-01
  • 2012-02-10
  • 2017-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多