我有连接数据库的功能。我也会检查是否经过,但是,当我故意失败时,它并没有打印出if(!$db)
括号中的错误。
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;
}
}
它打印出来自PHP的警告:Warning: mysqli::__construct(): (HY000/1045): Access denied for user 'root'@'localhost' (using password: NO)
我得到了。但为什么它仍然打印出来"好的"在else中,不应该调用printError吗?
答案 0 :(得分:1)
这里是处理错误的mysqli的php文档示例
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 . "\n";
$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 . "\n";
?>
答案 1 :(得分:0)
您的对象$ db不为null,因此这将始终打印'ok'。要检查数据库是否已连接,请在if语句中使用'$ db-&gt; connect_error'。
答案 2 :(得分:0)
你是通过说新的mysqli(...)来创建一个对象。您可以删除新部件,并可以像下面一样使用它。
<?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) . "\n";
mysqli_close($link);
?>