The question body makes no sense, as the code is inconsistent with the error message. For the code present, the error message would have been Warning: mysqli_select_db() expects parameter 1 to be mysqli, string given
.
That aside, it seems this question attracts many visitors who are genuinely getting the error from the question title. For them, here is a complete and proper guide on How to connect using mysqli:
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$mysqli = mysqli_connect($host, $user, $pass, $db);
mysqli_set_charset($mysqli, $charset);
} catch (\mysqli_sql_exception $e) {
throw new \mysqli_sql_exception($e->getMessage(), $e->getCode());
}
By following this routine, one would never ever get an error like this. As well as many other errors that would be induced by the code suggested in the other answers.
Important advantages of this code are
- as you can see, there is no need to
call mysqli_select_db()
function at all, as the database name could be supplied already in mysqli_connect()
.
- the proper error reporting mode is set, and therefore the actual error message will be reported, explaining why
mysqli_connect()
returned null
, hence you'll be able to fix the error.
- the proper charset must be always set
- and the connection error should be handled properly. Some mysqli internals is not what you really want for the site visitors to see.
The detailed explanation of all these issues could be found in the article linked above.