2016-08-09 33 views
0

您好,我有一個問題PDO連接。我conn.php是PDO連接:調用成員函數prepare()null

<?php 
define('host', 'localhost'); 
define('host_user', 'root'); 
define('host_pass', ''); 
define('host_db', 'testdb'); 
class Database { 
public $conn; 
public function Connect() { 
try { 
$conn = new PDO("mysql:host=" . host . ";dbname=" . host_db, host_user, host_pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); 
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
} catch (PDOException $e) { 
echo "Connection error:" . $e->getMessage(); 
} 
} 
} 
?> 

當我使用這個

$dbClass = new Database(); 
$stmt = $dbClass::Connect()->prepare("SELECT * FROM user_posts"); 

返回以下錯誤:

Call to a member function prepare() on null

爲什麼會發生?

回答

1

你得到一個錯誤,因爲prepare()PDO的功能,但由於Connect()不返回任何東西,你打電話prepare()就沒事。

您應該修改Connect(),以便它返回PDO對象。在函數的末尾添加(或Try塊的末尾):

return $conn; 
+0

感謝它的工作原理! – user3227899

+0

@ user3227899不客氣:-)請記住選擇我的答案,如果它可以幫助您解決問題。 – BeetleJuice

+0

選擇?什麼意思? – user3227899

相關問題