首页 > 解决方案 > 我的 SQL 语句正确但仍然返回错误

问题描述

在我的网站上,我尝试获取一些信息并将它们添加到我的数据库中,但是自从我将日期更改为 datetime 之后,整个 SQL 语句就不再起作用了。

我在网上到处查看,似乎没有其他人遇到同样的问题,我可能只是错过了一些东西,但 SQL 语句对我来说看起来是正确的。

public function addTimeLine($typeOfPost,$post,$idImage,$numberImage){
    $post = addslashes($post);
    $typeOfPost = addslashes($typeOfPost);
    $date = date("Y-m-d H:i:s");
    $query = "INSERT INTO `time_line` ( `special_note`, `type`, `id_image`, `number_image`, `dates`) VALUES ( '".$post."', '".$typeOfPost."', ".$idImage.", ".$numberImage.", '".$date."')";
    $ps = $this->_db->prepare($query);
    $ps->execute();
}

它给了我这个错误

致命错误:未捕获的 PDOException:SQLSTATE[42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 '1, '2019-07-12 16:29:58')' 附近使用正确的语法

标签: phpsql

解决方案


您没有正确使用准备好的语句。您需要使用占位符,然后在execute

public function addTimeLine($typeOfPost, $post, $idImage, $numberImage) {
    $date = date("Y-m-d H:i:s");
    $query = "INSERT INTO `time_line` ( `special_note`, `type`, `id_image`, `number_image`, `dates`) VALUES ( ?, ?, ?, ?, NOW())";
    $ps = $this->_db->prepare($query);
    $ps->execute([
        $post,
        $typeOfPost,
        $idImage,
        $numberImage
    ]);
}

推荐阅读