检查数据库连接,否则显示消息

2022-08-30 20:17:39

我想检查网站是否可以连接到mySQL。如果没有,我想显示一个错误,说用户应该在几分钟内再次尝试访问该页面...

我真的不知道该怎么做;)

任何帮助将不胜感激!

string mysql_error ([ resource $link_identifier ] )

但是我如何使用它呢?

这只会给我错误,但我希望消息显示任何错误。

谢谢


答案 1

试试这个:

<?php
$servername   = "localhost";
$database = "database";
$username = "user";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}
  echo "Connected successfully";
?>

答案 2

非常基本:

<?php 
$username = 'user';
$password = 'password';
$server = 'localhost'; 
// Opens a connection to a MySQL server
$connection = mysql_connect ($server, $username, $password) or die('try again in some minutes, please');
//if you want to suppress the error message, substitute the connection line for:
//$connection = @mysql_connect($server, $username, $password) or die('try again in some minutes, please');
?>

结果:

警告:mysql_connect() [function.mysql-connect]:用户“user”@'localhost“(使用密码:YES)在第6行的/home/user/public_html/zdel1.php访问被拒绝,请在几分钟内重试,请

根据Wrikken在下面的建议,请查看完整的错误处理程序,以获取更复杂,高效和优雅的解决方案:http://www.php.net/manual/en/function.set-error-handler.php


推荐