m1l4n
m1l4n

Reputation: 19

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

I am working on new PHP site, and I need help with this error.

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in ..

I have class Database.class, and one abstract class ActiveRecord.php.

    class Database {
    private static $instance = null;
    private function __construct(){}
    public static function getInstance(){
        if(!self::$instance){
            self::$instance = mysqli_connect(DBHOST, DBUSER, DBPASS, DB);
            return self::$instance;
        }
    }
}

And ActiveRecord class in new file.

        abstract class ActiveRecord {
    public function save() {
        $q = "UPDATE " . static::$table . " SET ";
        foreach($this as $k=>$v){
            if($k==static::$key) continue;
            $q.=$k."='".$v."',";
        }
        $q = rtrim($q,",");
        $keyField = static::$key;
        $q.=" WHERE ".static::$key." = " . $this->$keyField;
        mysqli_query(Database::getInstance(), $q);
    }
}

When I am testing save(); function I get Warning for mysqli. I created new file and write this in it.

    class Category extends ActiveRecord {
    public static $table = "categories";
    public static $key = "category_id";
}

$cat = Category::get(1);
$cat->name = "Action";
$cat->description = "Action Description";
$cat->save();

Problem is that in save() function Database::getInstane() not recognized. But if I put "mysqli_connect("localhost", "root", "", "db")" everything working fine and script updating database records.

Do anyone know what is the problem?

Upvotes: 1

Views: 175

Answers (1)

jagad89
jagad89

Reputation: 2643

Problem is you are not returning anything if instance already created.

Update your getInstance function as below

public static function getInstance(){
if(!self::$instance){ 
self::$instance = mysqli_connect(DBHOST, DBUSER, DBPASS, DB);
} 
return self::$instance; 
 }

Upvotes: 1

Related Questions