views:

33

answers:

4

I have the following code that is able to create a class that has a single static instance of the database object, and two static functions for rows and columns.

<?php class Database{

    private static $instance;

    private function __construct() {}
    private function __clone(){}

    public static function call(){
        if(!isset(self::$instance)){  
            self::$instance = new MySQLi("localhost", "foo", "bar", "fizz");  
            if(self::$instance->connect_error){  
                throw new Exception('Error MySQL: ' . self::$instance->connect_error);  
            }  
        } 
        return self::$instance;
    }

    public static function getRow($id, $db){
        $query = "SELECT * FROM ".$db." WHERE id=".$id;
        $result = self::call()->query($query);
        return $result->fetch_assoc();
    }
} ?>

However, when I call getRow from another class, like this

$data = Database::getRow($id, "posts");

I get the following error:

Fatal error: Call to a member function fetch_assoc() on a non-object in database.php on line 27

And I check it again and again and everything seems to be in order, maybe I have a error in call() ? help!!.

A: 

That will happen if you have an error in your SQL syntax -- did you check it and make sure there were no errors?

I would have error checking, something like

if( self::$instance->error ) {
    // Handle error
}
Kerry
A: 

You are passing in a variable called $db to getRow(), maybe that should be a table?

berty
$db is the name of the table
ONi
+1  A: 

query() will return false if the SQL query fails. You can add the following to handle this error:

$result = self::call()->query($query)
if($result === false)
    throw new Exception(call()->error); // throw exception, use MySQLi error as message

return $result->fetch_assoc();
rojoca
A: 

I have tried this code and it works, you must have an error in the query. What may cause this error is:

a) Check what you pass to Database::getRow(). There may be some non-numerical characters in your id.
b) Check if coulumn name 'id' exists, this sounds funny but it happened to me a million times, i was querying column 'id' instead of 'product_id' and so on.
c) Check if table $db exists.
d) Make sure you don't switch the function parameters by an accident. Database::getRow(24, 'people'); instead of Database::getRow('people', 24);.

I can't think of anything else that may cause this error.

cypher