gpt4 book ai didi

php - 如何捕捉 mysqli_connect() 的警告

转载 作者:行者123 更新时间:2023-12-04 00:34:18 24 4
gpt4 key购买 nike

我如何捕捉 mysqli_connect() 的警告

例子

if (!$connection2 = mysqli_connect($host, $username, $password, $name)){
die('MySQL ERROR: ' . mysql_error());
}

或者
$connection2 = mysqli_connect($host, $username, $password, $name);
if (!$connection2){
die('MySQL ERROR: ' . mysql_error());
}

所以,我正在尝试测试 mysqli_connect()方法是在其中放入错误的主机、用户名等。但是当我把错误的变量放进去时,比如我把 hostlocal而不是 localhost .它给了我这个错误

Warning: mysqli_connect(): php_network_getaddresses: getaddrinfo failed:
No such host is known.



我知道我在其中放置了错误的主机,但我想以适当的方式捕获错误。一个体面的消息将是完美的,就像:

Unfortunately, the details you entered for connection are incorrect!



那么,我如何收到此消息而不是警告,谢谢

最佳答案

其中之一,mysql_error()不会给你任何东西。它是另一个图书馆的一部分,mysql_ ,它不会与新的和改进的 mysqli_ 互换.话虽如此,您可以将 MySQLi 设置为抛出异常,然后您可以捕获这些异常。

如果启用了错误记录(应该如此!),警告仍然会被记录下来。但是,如果连接失败,您可以捕获错误并在页面上显示更用户友好的内容。您永远不应该向实时项目显示实际的错误消息 - 在开发中它很好,但绝不能在任何实时环境中显示。

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // Set MySQLi to throw exceptions 

try {
$connection2 = mysqli_connect($host, $username, $password, $name);
} catch (mysqli_sql_exception $e) {
// $e is the exception, you can use it as you wish
die("Unfortunately, the details you entered for connection are incorrect!");
}

但是,这会记录与您在日志中看到的相同的警告,

php_network_getaddresses: getaddrinfo failed: Name or service not known



虽然它不会显示在页面上。

您可以通过添加 @ 来抑制警告(因此它不会被记录) ,但除非您明确实现自己的错误处理/报告,否则我不推荐它。应该记录错误。
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // Set MySQLi to throw exceptions 

try {
$connection2 = @mysqli_connect($host, $username, $password, $name);
} catch (mysqli_sql_exception $e) {
error_log($e->getMessage()); // Log the error manually
die("Unfortunately, the details you entered for connection are incorrect!");
}
  • http://php.net/manual/en/class.mysqli-sql-exception.php
  • 关于php - 如何捕捉 mysqli_connect() 的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46146192/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com