连接数据库不会打印出错误

I have a function to connect to a DB. I also check if that went through, however, when I fail it intentionally, it doesn't print out the errors in the if(!$db) brackets.

function connectToDb(){
    //Connect to a database
    $db = new mysqli("localhost", "root", "", "vm_ski");
    if(!$db){
        echo "error: ConnectToDB failed";
        printError("Could not connect to db: ".$db->error);
    }
    else{
        echo "OK";
        return $db;
    }
}

It prints out the warning from PHP: Warning: mysqli::__construct(): (HY000/1045): Access denied for user 'root'@'localhost' (using password: NO) which I get. But why does it still print out "OK" in the else, shouldn't it call printError?

here is php document example of mysqli to deal with error

http://php.net/manual/en/mysqli.quickstart.connections.php

<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "
";

$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

echo $mysqli->host_info . "
";
?>

Your object $db is not null, so this will print 'ok' always. To check if the database was connected use '$db->connect_error' inside of if statement.

You are creating a object by saying as new mysqli(...). You can remove the new part and can use it like the following.

<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');

if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
        . mysqli_connect_error());
}

echo 'Success... ' . mysqli_get_host_info($link) . "
";

mysqli_close($link);
?>