【问题标题】:Handling MySQL errors in PHP [duplicate]在 PHP 中处理 MySQL 错误 [重复]
【发布时间】:2013-08-12 18:36:06
【问题描述】:

在开发我的网站时,我使用mysql_error() 来显示错误,以便我知道如何修复它们。

我的问题是......当网站上线时,我应该如何处理错误,因为我不希望用户看到错误,而是看到用户友好的消息,例如 “糟糕,出了点问题"

【问题讨论】:

  • if mysql error-> 你的处理脚本。

标签: php mysql error-handling


【解决方案1】:

首先,我强烈建议从已弃用的 mysql_ 函数转移到 MySQLiPDO 类之一。两者都更加安全,并且在 PHP 的当前和可预见的未来版本中得到维护。

显示错误的一些可能解决方案是:

$sql = new mysqli($host, $user, $password, $database);
$query = //your query

//Option 1
$result = $sql->query($query) or die("Something has gone wrong! ".$sql->errorno);
//If the query fails, kill the script and print out a user friendly error as well 
//as an error number for them to quote to admins if the error continues to occur, 
//helpful for debugging for you, and easier for users to understand

//Option 2
$result = $sql->query($query);
if($result) {
    //if the query ran ok, do stuff
} else {
    echo "Something has gone wrong! ".$sql->errorno;
    //if it didn't, echo the error message
}

您还可以使用 PHP error_log 函数将新错误放入错误日志中,其中可能包含完整的 $sql->error 详细信息供管理员查看,并完全跳过 $sql->errorno 打印输出。有关错误记录的更多信息,请查看PHP Docs

【讨论】:

    【解决方案2】:

    通常您希望在实时环境中记录这些错误(意思是,您将错误消息和一些进一步的信息(如时间、IP、..)写入文件) 在用户方面,您还应该向用户提供一些反馈,因此打印一个很好的错误消息,以便用户知道出了问题。

    只需使用 Google 查找一些 Logger 库。大多数情况下,它们可以配置为改变生活和开发环境中的行为! 你也可以看看:https://www.php-fig.org/psr/psr-3/

    【讨论】:

      【解决方案3】:

      在开发您的网站时,您不应使用 mysql_error(),因为您不应使用任何 mysql_* 函数,因为它们已被弃用。

      最基本的错误处理是抛出一个Exception。异常处理程序应将错误消息与stack trace 一起记录并输出错误页面。

      【讨论】:

        【解决方案4】:

        您需要处理从 SQL 查询中收到的答案。就像成功或错误一样。 像这样:

        <?php
            $response = 0;
            $con=mysqli_connect("localhost","my_user","my_password","my_db");
            // Check connection
            if (mysqli_connect_errno()){
                $response = "Failed to connect to MySQL: " . mysqli_connect_error();
            }
        
            // Perform a query, check for error
            if (!mysqli_query($con,"INSERT INTO Persons (FirstName) VALUES ('Glenn')")){
                $response = "Error description: " . mysqli_error($con);
            }
        
            mysqli_close($con);
        
            echo $response;
        ?>
        

        然后在您的前端,您可以使用 jQuery 插件或某些框架为您的响应提供格式。我推荐使用:jquery 确认。 参考: https://www.w3schools.com/php/func_mysqli_error.asp https://craftpip.github.io/jquery-confirm/

        如果要处理特定错误,请通过检测确切的错误编号代码来尝试。 https://dev.mysql.com/doc/refman/5.5/en/server-error-reference.html https://www.php.net/manual/es/mysqli.errno.php

        【讨论】:

          【解决方案5】:

          您可以使用: if (mysqli_error($conn)) { $error = 'Oops something went wrong!'; } echo $error;

          $conn 代表执行查询的数据库连接。

          【讨论】:

            猜你喜欢
            • 2019-11-26
            • 2012-02-04
            • 1970-01-01
            • 1970-01-01
            • 2023-03-06
            • 2015-10-03
            • 1970-01-01
            • 1970-01-01
            • 2013-01-14
            相关资源
            最近更新 更多