0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.