問題描述
我正在這樣做(是的,我使用了錯誤的連接數據,這是為了強制連接錯誤)
try {
$connection = new mysqli('localhost', 'my_user', 'my_password', 'my_db') ;
} catch (Exception $e ) {
echo "Service unavailable";
exit (3);
}
但是 PHP 正在這樣做 php_warning:
But PHP is doing this php_warning:
mysqli::mysqli(): (28000/1045): 用戶 'my_user'@'localhost' 訪問被拒絕(使用密碼:YES)
mysqli::mysqli(): (28000/1045): Access denied for user 'my_user'@'localhost' (using password: YES)
在示例中,我使用錯誤的連接數據來強制連接錯誤,但在現實世界中,數據庫可能已關閉,或者網絡可能已關閉......等等.
In the example I'm using wrong connection data to force a connection error, but in the real world the database could be down, or the network could be down... etc..
問題:有沒有辦法在不抑制警告的情況下攔截數據庫連接問題?
Question: Is there a way, without suppressing warnings, to intercept a problem with the database connection ?
推薦答案
你需要告訴mysqli拋出異常:
You need to tell mysqli to throw exceptions:
mysqli_report(MYSQLI_REPORT_STRICT);
try {
$connection = new mysqli('localhost', 'my_user', 'my_password', 'my_db') ;
} catch (Exception $e ) {
echo "Service unavailable";
echo "message: " . $e->message; // not in live code obviously...
exit;
}
現在您將捕獲異常并從那里獲取它.
Now you will catch the exception and you can take it from there.
這篇關于new mysqli():如何攔截“無法連接"錯誤?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!