【问题标题】:Trouble with php (call to a member function on a non-object)php问题(调用非对象的成员函数)
【发布时间】:2011-04-30 02:02:30
【问题描述】:

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

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

这里是调用函​​数prepare的那一行。

$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();
    }
}
}
?>

【问题讨论】:

  • 你需要发布更多的代码。我们看不到您在哪里/是否实际创建了您的语句对象。如果您认为类中有一个名为statement 的成员并不重要,重要的是您将对象分配给该成员的时间和地点 - 根据您尚未完成的错误。
  • 如果这只是一个围绕 PDO 或 mysqli 的包装类,那么您应该首先分配给 -&gt;statement。它通常是准备 SQL 查询的结果,而不是准备东西的句柄。

标签: php object fatal-error


【解决方案1】:

您分配了局部变量$statement。您需要使用$this-&gt;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();

【讨论】:

  • 也在$statement-&gt;bind_param("ss", $name, $feedback);$query = $statement-&gt;execute();里面preparedQuery()函数。
  • 发现另一行错误$query = $statement-&gt;execute(); :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-02
  • 2014-06-19
  • 1970-01-01
  • 2016-01-01
相关资源
最近更新 更多