【发布时间】:2017-06-18 05:01:37
【问题描述】:
我目前正在为一个学校项目用 PHP 构建一个评论系统,但我偶然发现了一个问题。我希望用户能够发布无需刷新即可插入的评论。我得到了这个工作。我还希望帖子加载所有 cmets,包括用户刚刚发布的那个。
我不知道如何做后者,所以这就是我在这里寻求建议/提示/示例的原因。
这是我现在用来加载当前帖子的所有 cmets 的代码。它正在工作,但我想以某种方式将其替换为具有相同功能但“实时”的 AJAX 代码。
include('dbconnect.php');
$stmt = $db->prepare("
SELECT c.comments_id, c.time, c.comment, c.date, c.posts_id, c.users_id, users.users_id, users.name, users.surname, users.profilepicture
FROM `comments` as c k
INNER JOIN users ON c.users_id = users.users_id
WHERE c.posts_id = ".$row["posts_id"]);
$stmt->execute();
$amtResults = $stmt->rowCount();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
echo '<div class="row">
<div class="column column-1">
<img style="padding-left:5px;padding-top:5px; height: 30px; width: 30px;" class ="commentuppic" src="/uploads/'.$row["profilepicture"].'" alt="Profile picture">
</div>
<div class="column column-9">
<p id="replytext">
<a href="profilefriend.php?user_id='.$row["users_id"].'">'.$row["name"].' '.$row["surname"].'</a>:<br>
'.$row["comment"].'
</p>
</div>
<div class="column column-1">
<form method="post">
<button type="submit" style="width: auto;" name="delete_comment" ><span class="fa fa-trash-o"></span></button>
<input type="hidden" name="comments_id" value="'.$row["comments_id"].'" />
</form>
</div>
</div>';
}
如果需要,这里是我用于将评论插入数据库的代码:
$("form[name='submit_comment']").submit(function (e) {
//do whatever you want to do when submitting comment
var comment = $('#comment').val();
var post_id = $('#post_id').val();
$.ajax({
url: 'insertmessage.php',
//async: true,
//cache: false,
data: {comment:comment, post_id:post_id},
type: 'POST',
});
return false;
});
和insertmessage.php:
if($_POST["comment"]){
include('dbconnect.php');
// set the PDO error mode to exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $db->prepare('INSERT INTO comments ( date, time, comment, posts_id, users_id ) VALUES ( :date, :time, :comment, :posts_id, :users_id )');
$date = date("Y/m/d");
$time = date("h:i:sa");
$stmt->bindValue(':date', $date, PDO::PARAM_STR);
$stmt->bindValue(':time', $time, PDO::PARAM_STR);
$stmt->bindValue(':comment', $_POST["comment"], PDO::PARAM_STR);
$stmt->bindValue(':posts_id', $_POST['post_id'], PDO::PARAM_INT);
$stmt->bindValue(':users_id', $_SESSION['users_id'], PDO::PARAM_INT);
$stmt->execute();
$db= null;
header('Location: profile.php');
}
感谢任何帮助!
编辑:我强烈推荐@David 他的解决方案,因为它运行良好且易于实施!
【问题讨论】:
-
您应该有一个带有
addComment端点的 REST api,然后执行添加评论的请求。然后,此请求将返回帖子中所有 cmets 的列表,您可以使用它来填充评论部分 -
实时数据通常适用于 NoSQL 数据库
-
您对此的具体问题是什么?你被困在哪里了?
-
@NicoHaase 这是一个老问题,已经解决了!