简体   繁体   English

防止mysql_connect()出错 - 访问被拒绝

[英]Prevent Error on mysql_connect() - Access denied

I have this code snippet: 我有这段代码:

$conn = mysql_connect($host, $usr, $pwd);

How can I prevent PHP from printing an error message when MySQL access is denied? 当MySQL访问被拒绝时,如何防止PHP打印错误消息?

I need exactly this syntax but nothing works for me. 我需要这个语法,但没有什么对我有用。

I tried $conn = mysql_connect($host, $usr, $pwd) or false; 我试过$conn = mysql_connect($host, $usr, $pwd) or false; and $conn = mysql_connect($host, $usr, $pwd) || false; $conn = mysql_connect($host, $usr, $pwd) || false; $conn = mysql_connect($host, $usr, $pwd) || false; and the following: 以下内容:

try {
    $conn = mysql_connect($host, $usr, $pwd);

    if(!$conn) {
        throw new Exception('Failed');
    }
} catch(Exception $e) {
    // ...
}

PHP always prints an error message that the connection failed. PHP始终打印连接失败的错误消息。 But I just want to return false, if it failed. 但是如果它失败了,我只想返回false。

Error printing should not be activated on a production server. 不应在生产服务器上激活打印错误。 Consider changing your php.ini configuration to log error instead of displaying it. 考虑更改php.ini配置以记录错误而不是显示它。

Using @ to silent error message is not a good solution. 使用@ to silent错误消息不是一个好的解决方案。

I don't know why you want to, but you can add a @ to surpress php errors? 我不知道你为什么要这样,但你可以添加@来压制php错误吗?

see: http://php.net/manual/en/language.operators.errorcontrol.php 请参阅: http//php.net/manual/en/language.operators.errorcontrol.php

You shouldn't really be using mysql_connect in PHP 5, as its now deprecated in favour of mysqli and PDO. 你不应该在PHP 5中使用mysql_connect ,因为它现在已经弃用了mysqli和PDO。

But you can probably silence the warning generated by mysql_connect by prefixing with @ : 但你可以通过前缀@来使mysql_connect生成的警告静音:

@mysql_connect()

The @ suppresses errors. @抑制错误。 And also set error reporting error_reporting(0); 并设置错误报告error_reporting(0); to turn off all errors. 关闭所有错误。 Also check out mysqli 还可以看看mysqli

Docs 文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM