mysqli can succeed in surprising ways, depending on the privileges granted to the user. For example,
GRANT USAGE ON *.* TO 'myuser'@'localhost' IDENTIFIED BY PASSWORD 'mypassword';
GRANT ALL PRIVILEGES ON `database_a`.* TO 'myuser'@'localhost';
CREATE DATABASE database_b;
<?php
$db = new mysqli('localhost', 'myuser', 'mypassword', 'database_b');
if ($db->connect_error) {
die('Connect Error (' . $db->connect_errno . ') '
. $mysqli->connect_error);
}
printf("SQLSTATE: %s\n", $this->db->sqlstate);
printf("Warning Count: %s\n", $db->warning_count);
$db->close();
?>
Will output:
SQLSTATE: 00000
Warning Count: 0
So, life is good — you're connected to the database and executing mysqli methods. Except, life isn't good, because you aren't actually using database_b because myuser doesn't have any privileges on it. You won't catch this until you try to perform a later operation, when you'll get an error, "MYSQL Error: No database selected", and find yourself scratching your head and thinking "what do you mean, of course I have a database selected; I selected one when I called the constructor".
As a result, you may want to perform an additional check after connecting to mysql, to confirm that you're actually connected not just to the mysql server, but to the actual database:
<?php
$db = new mysqli('localhost', 'myuser', 'mypassword', 'database_b');
if ($db->connect_error) {
die('Connect Error (' . $db->connect_errno . ') '
. $mysqli->connect_error);
} elseif ($result = $db->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
if ($row[0] != 'database_b') {
}
}
?>