PHP评论系统

时间:2018-02-12 04:22:37

标签: php mysql

我正在尝试用PHP和Mysql构建一个评论系统。我想链接一篇帖子和许多评论。所以我有一个帖子表和一个评论表。 comments表有一个post_id的外键,类似于posts table id列(posts表中的主键)。管理员添加帖子后,将插入post_id列,其中包含该帖子的ID。这意味着在添加注释时,有人必须更新注释表,在我的情况下,它不会。这是更新查询。

if(isset($_POST['cmt-btn'])){
if(!empty($_GET['id'])){
    $current_id = $_GET['myid'];
    echo $current_id;
    $comment = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);
    $author = filter_var($_POST['author_name'], FILTER_SANITIZE_STRING);
    $post_id = $current_id;
    $time = now();  
    $sql = "UPDATE comments SET comments = '$comment', author = '$author', timeposted = '$time' WHERE post_id = '$current_id'";
    $result = $connection->query($sql);
}

注释表只是用NULL填充空列。 我似乎没有追查问题所在。

1 个答案:

答案 0 :(得分:1)

首先你需要插入而不是更新并使用prepare语句来防止SQL注入请找到这样做的代码

$comment = "This is Comment";
$author = "Nikita";
$post_id = 1;
$time = "12:00:00";

function insertComment($comment,$author,$post_id,$time){
  global $mysqli;
  $stmt = $mysqli->prepare("INSERT INTO comments(
    comments,
    author,
    timeposted,
    post_id
     )VALUES (
      ?,
      ?,
      ?,
      ?
    )");
    $stmt->bind_param("ssss",$comment,$author,$post_id,$time);
    $stmt->execute();
    $inserted_id = $mysqli->insert_id;
    return $instered_id;
 }
 $sql = insertComment($comment,$author,$post_id,$time);
 echo $sql;
相关问题