PHP - 如果没有MySQL Connection则显示简单消息

时间:2016-05-22 20:20:58

标签: php mysql

如何在连接数据库时显示简单的短信时捕获并忽略错误?

我的连接看起来像这样:

$connection = mysqli_connect($dbhost, $dbuser, $dbpw, $dbname);

如果连接失败,我希望它只是回显"错误连接到数据库"而不是大错误框。

编辑:

尽管error_reporting(0)确实有效,但更好的方法就是放置' @'在mysqli_connect前面:

$connection = @mysqli_connect($dbhost, $dbuser, $dbpw, $dbname);
    if (!$connection) {
        $connection_status = 'Connection to database failed';
    } else {
        $connection_status = null;
    }

?>
<?php echo $connection_status; ?>

3 个答案:

答案 0 :(得分:4)

取自{{3}}的文件:

  

实施例

     

示例#1 mysqli_connect()示例

<?php
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");

if (!$link) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}

echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;

mysqli_close($link);
?>

答案 1 :(得分:1)

mysqli_connect

$connection = mysqli_connect($dbhost, $dbuser, $dbpw, $dbname);
if (!$connection)
{
    error_reporting(0);
    die("Error: Unable to connect to MySQL." . PHP_EOL);
}

禁用&#34;大错误框&#34; (我假设标准消息?),在此上面写error_reporting(0);

答案 2 :(得分:1)

您可以为错误设置自定义处理程序

register_shutdown_function("shutdownHandler");
function shutdownHandler()
{
    if (!is_null($e = error_get_last())).
    {
        echo $e['message'];
    }
}