在PHP预处理语句中调用boolean上的成员函数bindParam()

时间:2017-07-12 07:54:52

标签: php mysql pdo prepared-statement

所以我在参考w3schools之后尝试PDO项目,但我一直收到这个错误

  

在布尔值

上调用成员函数bindParam()

这是我的代码。我无法弄清楚是什么导致它

if (isset($data->title) && isset($data->content) && isset($data->lang) && isset($data->show_on_site)) {
    $response = array();
    try {
        $sql = 'INSERT INTO newsposts
            (heading, content, author, language,show_on_page)
             VALUES (:title, :content,:author,:lang,:show_on_site)';

        $stmt = $db->prepare($sql);
        $stmt->bindParam(':title', $db->real_escape_string($data->title), PDO::PARAM_STR);
        $stmt->bindParam(':content', $db->real_escape_string($data->content), PDO::PARAM_STR);
        $stmt->bindParam(':author', $_SESSION['user_session'], PDO::PARAM_STR);
        $stmt->bindParam(':lang', $db->real_escape_string($data->lang), PDO::PARAM_STR);
        $stmt->bindParam(':show_on_site', $db->real_escape_string($data->show_on_site), PDO::PARAM_BOOL);

        if ($stmt->execute()) {
            header_status(200);
            $response['status'] = 'Success';
            $response['message'] = 'Post Inserted';
        } else {
            header_status(400);
            $response['status'] = 'Error';
            $response['message'] = 'Something went wrong';
        }
        echo json_encode($response);
    } catch (exception $e) {
        header_status(503);
        $response['status'] = 'Error';
        $response['message'] = $e->getMessage();
        echo json_encode($response);
    }

1 个答案:

答案 0 :(得分:0)

As documentation states:

If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).

so try to set "error mode" in your $db object to "exception" with

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

and wrap prepare() call in "try-catch" block to figure out what's going wrong, like this

try {
    $stmt = $db->prepare($sql);
} catch (PDOException $e) {
    echo $e->getMessage();
}