【发布时间】:2019-08-07 12:22:42
【问题描述】:
我在我的数据库中有一个用于帖子的表,另一个用于 cmets 的表,我想做的是从数据库中获取所有帖子,并且对于每个帖子,我都提供了一个表单来提交 cmets。当我尝试使用带有 ajax 的此表单发布 cmets 时,它仅适用于一个帖子而不适用于其他帖子。(在这里我想提一下,由于每个帖子都会自动填充此表单,因此其文本区域具有相同的 ID ,可能这可能会导致错误)但我不知道如何解决这个问题?任何帮助或建议将不胜感激。
(注意:我不是专家,只是学习者。)
这是我的代码:
<?php
echo '<div class="'.$row['post_id'].'">';
$connect = mysqli_connect("localhost", "root", "", "testing") or die("<p><span style=\"color: red;\">Unable to select database</span></p>");
$post_id = $row['post_id'];
$resultt = mysqli_query($connect,"SELECT * FROM tbl_comment WHERE parent_comment_id = '0' AND post_id = '$post_id' ORDER BY comment_id DESC ");
while($rowss = mysqli_fetch_array($resultt, MYSQLI_BOTH))
{
if ($rowss>0){
echo '
<div>
<div>'.$rowss["comment"].'</div>
<div style="font-size: 12px; font-family: serif;">By <b>'.$rowss["comment_sender_name"].'</b> on '.$rowss["date"].'</div>
<div align="right" style="margin-bottom: 19px;"><a href="#" class="reply" id="'.$rowss["comment_id"].'">Reply</a></div>
</div>
';
} else { echo ''; } }
echo '</div>
<form method="POST" class="comment_form">
<div class="form-group"><textarea name="comment_content" class="form-control comment_content" post_id ="'.$row['post_id'].'" placeholder="Enter Comment" rows="2"></textarea></div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-info" value="Publish" onClick="adcomnt()" />
</div>
</form>
<script>
function adcomnt() {
var post_id = $(".comment_content").attr("post_id");
var comment_name = '.$_SESSION['username'].';
var comment_content = $(".comment_content").val();
var comment_id = 0;
$.ajax({
type: "POST",
url: "add_comment.php",
dataType: "json",
data: "post_id=" +post_id+ "&comment_content=" + comment_content+ "&comment_id=" + comment_id+ "&comment_name=" + comment_name,
success: function(data) {
if(data.status == "error"){
alert("Oops, Comment not inserted!");
}
else if(data.status == "success"){
alert("Thank you! comment inserted!");
}},
});
}
</script>
</div>';
?>
【问题讨论】:
-
警告:您对SQL Injections 持开放态度,应该真正使用参数化的prepared statements,而不是手动构建查询。它们由PDO 或MySQLi 提供。永远不要相信任何类型的输入,尤其是来自客户端的输入。即使您的查询仅由受信任的用户执行,you are still in risk of corrupting your data。
-
感谢您的建议,正如我所说,我正在学习东西,一定会研究这个。