简体   繁体   中英

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?

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; 
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM