我正在创建一个包含不同电影的网站,每个电影都有一个特定的id_movie,我添加了一个评论框,用户可以在其中添加有关该电影的评论,但是,我单击的每个电影都显示相同的评论,进入后,我希望每部电影都有自己的评论,如果您能帮助我,我会很高兴。谢谢
comments.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'); ?>
最佳答案
我会尽力而为,但有很多要讲的。
comments.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)。两者都使用只会给您的应用程序增加不必要的复杂性(我认为其中有两个):$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.
上面我建议为数据库使用一个文件,就您而言,这可能非常简单,
db.php
<?php $con = new PDO('mysql:host=localhost;dbname=db_movie', 'root', '');
这实际上就是您所需要的,然后在使用数据库的每一页的顶部,只需添加此文件
require_once 'db.php';
这样,如果您需要更改密码或类似的密码,则可以以易于记忆的方式转到一个命名的地方并进行更改。现在情况如何,您将不得不挖掘所有代码来进行更改。在该页面中,您包括一个名为
header.php
的文件,从您的MySQLi代码看来,其中可能包含一些连接内容。我也会在那里删除任何MySQLi内容。您想将数据库文件分开,因为可能需要将其包含在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
:插入评论
用户使用
?id=12
转到网址?
之后的所有内容都称为查询字符串PHP知道采用查询字符串并填充全局全局
$_GET
因此在主页上,您的电影ID现在为
$_GET['id']
我们通过一些基本检查将其本地化(创建局部变量)在页面顶部。
$movie_id = isset($_GET['id']) ? $movie_id : false;
如果将电影ID设置为
?id=12
,则将其放入$movie_id
如果不是
www.example.com/movies
,则将$movie_id
设置为false如果有人去没有该页面的页面,这可以避免一些错误
在页面底部,您包含此文件
<?php include('comments.php'); ?>
就像将代码粘贴到该位置一样在上面包含的
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" >
该页面上的ID将为
$_POST['movie_id']
。 $_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" />
现在在
add_comment.php
上(表单操作将执行此操作),我们可以将该$_POST['movie_id']
并将其添加到用于从#4中的表单中插入注释的SQL中。进入数据库。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中,我们可以通过调用它的$statement
方法或$statment=$conn->prepare($sql)
将其提供给您从execute
返回的PDOStatment对象($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都是一样的
在
comments.php
中,调用load_comment();
“之后”,定义不存在的函数会告诉您执行此操作,因此您不能在之前调用它。这将运行您的AJAX请求
$.ajax
,就本示例而言,它就像是一种处理表单的理想方式。 url
是action
的形式,method
是方法。 data
是表单数据,dataType
是这种情况下的编码类型JSON
或Javascript对象表示法。这是一种表达结构化数据的好方法,例如在PHP中,它基本上是一个数组(或带有嵌套元素的数据)。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 IS 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
然后,我们将结果取回,并使用
success
将其发送回AJAX的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倍的努力来教您所有的工作原理,然后发布一些您不知道它如何工作的代码。
希望一切都有意义。
关于javascript - 如何在不同页面上发表不同意见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55132727/