有没有办法在 PHP 中捕获 MySQL 和数据库错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6120589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:24:21  来源:igfitidea点击:

Is there any way to catch MySQL and database errors in PHP?

phpmysqlerror-handlingmysql-error-1045

提问by ASD

Sometimes I am getting a database error like

有时我会收到数据库错误,例如

Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'test'@'101.190.193.83' (using password: YES)

Could not connect: Access denied for user 'test'@'101.190.193.83' (using password: YES)"

警告:mysql_connect() [function.mysql-connect]:用户 'test'@'101.190.193.83' 访问被拒绝(使用密码:YES)

无法连接:用户 'test'@'101.190.193.83' 的访问被拒绝(使用密码:YES)”

But truly there is no change in the password.

但确实密码没有变化。

Is there any way to capture this error in a log file and show some nice message on the screen, like "Server error. Please try again some time."

有什么方法可以在日志文件中捕获此错误并在屏幕上显示一些不错的消息,例如“服务器错误。请稍后再试。”

回答by Gérald Cro?s

If you don't want PHP to show the warning, you have to use the "@" operator

如果您不想让 PHP 显示警告,则必须使用“@”运算符

$connect = @mysql_connect(HOST, USER, PASS);//won't display the warning if any.
if (!$connect) { echo 'Server error. Please try again sometime. CON'; }

You may also consider setting display_errorsto 0 in your php.inifile in production

您也可以考虑在生产中的文件中将 display_errors设置为 0php.ini

You may also consider PDOfor connecting to MySQL, it's using exceptions as a default to report errors,

您也可以考虑使用PDO来连接 MySQL,它使用异常作为默认报告错误,

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Could not connect : ' . $e->getMessage();
}

回答by ChrisH

<?php
    $connect = mysql_connect(HOST, USER, PASS);
    if(!$connect) { echo 'Server error. Please try again sometime. CON'; }

    $select_db = mysql_select_db(DATABASE);
    if(!$select_db) { echo 'Server error. Please try again sometime. DB'; }
?>

回答by Spudley

Is there any way to capture these error in to log file ... ?

有什么方法可以将这些错误捕获到日志文件中...?

Yes. All PHP errors and warnings are written to the web server's error log file, so there's nothing else you need to do -- it's already being done.

是的。所有 PHP 错误和警告都写入 Web 服务器的错误日志文件,因此您无需执行任何其他操作 —— 它已经完成。

To answer the second part of your question, if you don't want the raw error message displayed on the screen, you can prevent this in one of two ways:

要回答问题的第二部分,如果您不希望屏幕上显示原始错误消息,您可以通过以下两种方式之一防止这种情况发生:

  1. Use the @symbol in front of your function call -- ie $db = @mysql_connect(...);. This will turn error reporting off just for that specific function call. It's generally considered to be a bad idea to over-use this technique, but it is a legitimate thing to do occasionally.

  2. The better option may be to turn the global error reporting flag off, either in your PHP.ini, in your local .htaccessfile, or using ini_set()within the program.

  1. @在函数调用前使用符号 - 即$db = @mysql_connect(...);。这将仅为该特定函数调用关闭错误报告。过度使用这种技术通常被认为是一个坏主意,但偶尔这样做是合理的。

  2. 更好的选择可能是关闭全局错误报告标志,无论是在您PHP.ini的本地.htaccess文件中,还是ini_set()在程序中使用。

Typically, error reporting on the web page should only be used while you're developing the site. Once the site goes live, you should turn error reporting, so that you don't get PHP errors showing up in random places in your carefully constructed page layout in front of your customers. Any errors that occur will still be written to the server error log, but won't be displayed on the page.

通常,网页上的错误报告应仅在您开发站点时使用。一旦站点上线,您应该打开错误报告,这样您就不会在客户面前精心构建的页面布局中的随机位置显示 PHP 错误。发生的任何错误仍将写入服务器错误日志,但不会显示在页面上。

For MySQL errors, such as the one you've got, you can still get at the error itself within the program by using the mysql_error()function. This will contain the details of the last error to occurr, so you can programmaticaly check for it and report a sensible error message.

对于 MySQL 错误,例如您遇到的错误,您仍然可以使用该mysql_error()函数在程序中获取错误本身。这将包含最后发生的错误的详细信息,因此您可以以编程方式检查它并报告合理的错误消息。

回答by improgrammer

Source : http://wallstreetdeveloper.com/php-database-connection/

来源:http: //wallstreetdeveloper.com/php-database-connection/

Here is a sample code for database connectivity in php:

以下是 php 中数据库连接的示例代码:

<?php
//Step-1 : Create a database connection
$connection=mysql_connect(“localhost”,”root”,”root”);
if(!$connection) {
    die(“Database Connection error” . mysql_error());
}
//Step-2 : Select a database to use
$db=mysql_select_db(“widget_corp”,$connection);
if(!$db) {
    die(“Database Selection error” . mysql_error());
}
?>
<html>
<head>
<title>Database</title>
</head>
<body>
<?php
 //Step 3 : Perform database Queury
 $result=mysql_query(“select * from subjects”,$connection);
if(!$result) {
    die(“No rows Fetch” . mysql_error());
}

//Step 4 : Use returned data
while($row=mysql_fetch_array($result))
{
     //echo $row[1].” “.$row[2].”<br>”;
    echo $row["menu_name"].” “.$row["position"].”<br>”;
}

?>
</body>
</html>
<?php
//Step 5 : Close Connection
mysql_close($connection);
?>

回答by Ravi MCA

try {
    $dbh = new PDO($dsn, $user, $password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);// if your are not set this attributes you won't get any exceptions.
} catch (PDOException $e) {
    echo 'Server error. Please try again some time.';
}