2013-03-11 153 views
-1

有人能指出我在正确的方向,为什么下面这段代码失败..致命错误:调用成员函数的非对象准备

MySQLDb.php:

class MySQLDb 
{ 
     protected $_mysql; 
     protected $_query; 


     function __constructor($host,$username,$password,$db) 
     { 
      $this->_mysql = new mysqli($host,$username,$password,$db) or die('Problem connecting to the DB.'); 

     } 


     function query($query) 
     { 
      $this->_query = filter_var($query,FILTER_SANITIZE_STRING); 
      $stmt = $this->_prepareQuery(); 
      $stmt->execute(); 
      $results = $stmt->_dynamicBindResult($stmt); 
     } 


protected function _prepareQuery(){ 

      $dbh = $this->_mysql; 
      if (!$stmt = $dbh->prepare($this->_query)) { 
       trigger_error('Problem preparing query', E_USER_ERROR); 

      } 

      return $stmt; 
     } 

的index.php:

require_once('MYSQLDb.php'); 

$Db = new MySQLDb('localhost','root','','blog'); 


$results =$Db->query("SELECT * FROM posts"); 

当我运行程序它吐出来的是错误fatal error: call to a member function prepare on a non-object at if (!$stmt = $dbh->prepare($this->_query)) {

我正试图学习面向对象的方法来做这件事情,所以没有非常详细地介绍如何解决这个问题。

谢谢。

+0

'新的mysqli()'不会返回false如旧'的mysql_connect()',所以你'或死亡()'将不会被触发。你需要做'if(mysqli_connect_error()){die(mysqli_connect_error()); }'这可能是一个连接问题,但是你的错误处理没有达到你期望的水平。 – 2013-03-11 01:39:09

回答

4

的问题是在构造函数:

function __constructor($host,$username,$password,$db) { 

实际PHP“类的构造函数”的名字是__construct,不__constructor,那么你的版本是永远不会被调用和$this->_mysqlnull(即 - 不是对象) 。

尝试更新的功能,下面,它应该工作:

function __construct($host,$username,$password,$db) { 
相关问题