0

我收到了这个 php 错误,我似乎无法修复它。

Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\mlrst\database.php on line 26

这是调用函数准备的行。

$this->statement->prepare($strQuery);

这是它被宣布的。

protected $statement;

有任何想法吗?

编辑:这是我的完整代码(不要介意测试假人)

    <?php

$d = new database(); // test

class database {

protected $db_connect;
protected $statement;

function database() {
    $db_connect = new MySQLi("localhost", "root" ,"", "test") or die("Could not connect to the server.");
    $statement = $db_connect->stmt_init();
    $this->preparedQuery("INSERT INTO feedback (name, feedback) VALUES ('?', '?')");
    $this->close();
    echo "Done!";
}

protected function cleanString($strLine) {
    $strCleansedLine = preg_replace("/[^a-zA-Z0-9\s]/", "", $strLine);
    return $strCleansedLine;
}

public function preparedQuery($strQuery, $parameters = NULL) {
    try {
        $this->statement->prepare($strQuery);
        $statement->bind_param("ss", $name, $feedback);

        for ($i = 0; $i < count($parameters); $i++) {

        }
        $name = $this->cleanString("this is my name");
        $feedback = $this->cleanString("this is some feedback");
        $query = $statement->execute();
    } catch(Exception $e) {
        echo $e->getMessage();
    }
}

protected function close() {
    try {
        if ($this->statement != NULL)
            $this->statement->close();
        if ($this->db_connect != NULL)
            $this->db_connect->close();
    } catch (Exception $e) {
        $e->getMessage();
    }
}
}
?>
4

1 回答 1

4

您分配了局部变量$statement。您需要使用 设置实例的属性$this->statement

换句话说,改变这个:

$statement = $db_connect->stmt_init();

对此:

$this->statement = $db_connect->stmt_init();

还有这个:

$statement->bind_param("ss", $name, $feedback);

对此:

$this->statement->bind_param("ss", $name, $feedback);

...还有这个:

$query = $statement->execute();

对此:

$query = $this->statement->execute();
于 2011-04-30T02:16:11.803 回答