Getting error on binding param in select statement

2019-03-07 06:38发布

问题:

I have added a select snippet below. Why am I getting the following error on bind_param()?

Uncaught Error: Call to a member function bind_param() on boolean

Code:

$sessien = $_POST['xsession'];
$conn = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
$query = "SELECT `post` FROM `user` WHERE session=? ORDER BY `thedate` DESC ";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $sessien);
$stmt->execute();
while ($stmt -> fetch()) {
        echo "$post<br>";
}
$stmt->close();
$conn->close();

回答1:

Mysqli prepare can returns false before bind you must check it for errors. look at this article in php.net

http://php.net/manual/en/mysqli.error.php

    $sessien = $_POST['xsession'];
    $conn = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
    /* check connection */
    if ($conn->connect_errno) {
        printf("Connect failed: %s\n", $conn->connect_error);
        exit();
    }
    $query = "SELECT `post` FROM `user` WHERE session=? ORDER BY `thedate` DESC ";
    $stmt = $conn->prepare($query);
    if ($stmt) {
        $stmt->bind_param("s", $sessien);

        //bind Response variables
        $stmt->bind_result($post);
        $stmt->execute();
        while ($stmt -> fetch()) {
                echo "$post<br>";
        }
        $stmt->close();
    }else{
           //error
           var_dump($conn->error);
    }