1

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

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

4

5 回答 5

3

首先,我强烈建议从不推荐使用的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
}

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

于 2013-08-11T09:23:04.917 回答
2

Normally you want to log these errors in a live enviroment (meaning, you write the error message and some further infromation like time, ip, .. to a file) On the userside you should also provide the User some feedback, so print a nice error message so that the user knows that something went wrong.

Just use Google to find some Logger-libraries. Mostly, they can be configured to change behaviour in live and development enviroment! You might also have a look at: https://www.php-fig.org/psr/psr-3/

于 2013-08-11T08:56:48.437 回答
0

While developing your website, you should not use mysql_error(), because you should not use any of the mysql_* functions, because they are deprecated.

The most basic error handling is to throw an Exception. The exception handler should log the error message along with a stack trace and output an error page.

于 2013-08-11T08:57:56.490 回答
-1

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

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

于 2020-05-26T02:49:37.437 回答
-1

您需要处理从 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

于 2019-05-08T23:37:20.037 回答