2011-04-30 97 views
0

我得到這個PHP錯誤,我似乎無法修復它。麻煩用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(); 
    } 
} 
} 
?> 
+0

你將要需要發佈更多的代碼比的。我們無法看到在哪裏/如果你真的創建了你的語句對象。不管你是否已經聲明類中有一個名爲'statement'的成員,它在何時以及何處將對象分配給該成員時非常重要 - 根據你尚未完成的錯誤,它是非常重要的。 – prodigitalson 2011-04-30 02:10:56

+0

如果這只是一個圍繞PDO或mysqli的包裝類,那麼你應該首先分配給' - >語句'。它通常是準備SQL查詢的*結果*,而不是用於準備某些內容的句柄。 – mario 2011-04-30 02:14:01

回答

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(); 
+1

也在'$ statement-> bind_param(「ss」,$ name,$ feedback);''和'$ query = $ statement-> execute();''preparedQuery()'函數內部。 – morgar 2011-04-30 02:18:20

+0

@morgar:的確。添加。 – icktoofay 2011-04-30 02:21:26

+0

發現另一個錯誤的行'$ query = $ statement-> execute();':) – morgar 2011-04-30 02:22:43