mysqli中的“没有数据库选择”(php)

i get the "No database selected" using mysqli in php, i have this method:

private static $db_server = "localhost";
private static $db_usuario = "root";
private static $db_clave = "";
private static $db_base = "test";
private static $db = null;
public static function conectar_db() {
    if (self::$db == null) {
        self::$db = new mysqli(self::$db_server,self::$db_usuario,self::$db_clave,self::$db_base);
        self::$db->connect();
    }
    return self::$db;
}

and this code in another file to execute a query:

    $db = Core::conectar_db();
    $r = $db->query("SELECT * FROM usuarios");
    echo $db->error;//temporal
    while ($row = $r->fetch_array()) {
        var_dump($row);
        echo "<br>";
    }

and when executing the code the complete output is:

    No database selected
Fatal error: Call to a member function fetch_array() on a non-object in Path\to\my\file.php on line 6

but if i change the query to test.usuarios instead of usuarios it works (i'm using var_dump just for testing), i tried:

  • using public static $db and accesing directly to Core::$db (Core is a class to handle these core functionality)
  • using &conectar_db in method's signature
  • adding an invalid database name to $db_base and i got an error saying that db is invalid as expected i must use oop (i think using procedural style would have the same results as oop methods) because this is a project

Don't call self::$db->connect(). The mysqli constructor connects to the server. The connect method is actually equivalent to the constructor, so you're reconnecting with default parameters when you call connect() with no arguments.