创建错误后无法显示错误消息

发布于 2025-01-22 19:56:01 字数 537 浏览 1 评论 0原文

我正在尝试使用Localhost连接到数据库。

<?php
     //Connecting to the Database
     $servername = "localhost";
     $username = "root";
     $password = "";

    // Create a connection
    $conn = mysqli_connect($servername, $username, $password);

    // Die if connection was not successful
    if (!$conn){
        die("Sorry we failed to connect: ". mysqli_connect_error());
    }
    else{
        echo "Connection was successful";
    }
?>

如果建立连接,它可以工作,但我不明白 当我故意创建错误时,“对不起,我们无法连接”消息。

这可能是什么原因?

I'm trying to connect to the database using localhost.

<?php
     //Connecting to the Database
     $servername = "localhost";
     $username = "root";
     $password = "";

    // Create a connection
    $conn = mysqli_connect($servername, $username, $password);

    // Die if connection was not successful
    if (!$conn){
        die("Sorry we failed to connect: ". mysqli_connect_error());
    }
    else{
        echo "Connection was successful";
    }
?>

It works if the connection is made but I don't get the
"Sorry we failed to connect" message when I intentionally create an error.

What could be the potential causes of this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜光 2025-01-29 19:56:01

documentation ::

如果已启用mysqli_report_strict并尝试连接到请求的数据库失败,则抛出mySQLI_SQL_EXCEPTION。

由于您有例外,因此必须设置此设置。在这种情况下,您的代码应如下更改:

try {
    $conn = mysqli_connect($servername, $username, $password);
} catch(mysqli_sql_exception $e) {
    die("Sorry we failed to connect: ". mysqli_connect_error());
}
echo "Connection was successful";

As stated in the documentation:

If MYSQLI_REPORT_STRICT is enabled and the attempt to connect to the requested database fails, a mysqli_sql_exception is thrown.

Since you are getting an exception, this must be set. Your code should change as follows in this case:

try {
    $conn = mysqli_connect($servername, $username, $password);
} catch(mysqli_sql_exception $e) {
    die("Sorry we failed to connect: ". mysqli_connect_error());
}
echo "Connection was successful";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文