-1

Can somebody point me in the right direction as to why the following piece of code is failing..

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");

When I run the program it spits out the error fatal error: call to a member function prepare on a non-object at if ( !$stmt = $dbh->prepare($this->_query) ) {

I'm trying to learn the object oriented way of doing this things so not very clued in on how to troubleshoot this.

thanks.

tereško
  • 58,060
  • 25
  • 98
  • 150
greenpool
  • 553
  • 4
  • 17
  • 33
  • `new mysqli()` won't return false like the old `mysql_connect()`, so your `or die()` won't be triggered. You need to do `if (mysqli_connect_error()) { die (mysqli_connect_error()); }` This is likely a connection problem, but your error handling doesn't do what you expect... – Michael Berkowski Mar 11 '13 at 01:39

1 Answers1

4

The problem is in your constructor:

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

The actual PHP "class constructor" name is __construct, not __constructor, so your version is never being called and $this->_mysql is null (i.e. - not an object).

Try update the function to the following and it should work:

function __construct($host,$username,$password,$db) {
newfurniturey
  • 37,556
  • 9
  • 94
  • 102