我想检查网站是否可以连接到mySQL。如果没有,我想显示一个错误,说用户应该在几分钟内再次尝试访问该页面...
我真的不知道该怎么做;)
非常感谢任何帮助!
string mysql_error ([ resource $link_identifier ] )
但我该怎么用?
这只是给了我错误,但我希望显示消息时出现任何错误。
由于
答案 0 :(得分:47)
试试这个:
<?php
$servername = "localhost";
$database = "database";
$username = "user";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
答案 1 :(得分:6)
非常基本:
<?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]:第6行/home/user/public_html/zdel1.php中用户“user”@“localhost”(使用密码:YES)拒绝访问 请稍后再试一次
根据Wrikken的建议,请查看完整的错误处理程序,以获得更复杂,更高效,更优雅的解决方案:http://www.php.net/manual/en/function.set-error-handler.php
答案 2 :(得分:0)
请检查:
$servername='localhost';
$username='root';
$password='';
$databasename='MyDb';
$connection = mysqli_connect($servername,$username,$password);
if (!$connection) {
die("Connection failed: " . $conn->connect_error);
}
/*mysqli_query($connection, "DROP DATABASE if exists MyDb;");
if(!mysqli_query($connection, "CREATE DATABASE MyDb;")){
echo "Error creating database: " . $connection->error;
}
mysqli_query($connection, "use MyDb;");
mysqli_query($connection, "DROP TABLE if exists employee;");
$table="CREATE TABLE employee (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
$value="INSERT INTO employee (firstname,lastname,email) VALUES ('john', 'steve', 'johnsteve@yahoo.com')";
if(!mysqli_query($connection, $table)){echo "Error creating table: " . $connection->error;}
if(!mysqli_query($connection, $value)){echo "Error inserting values: " . $connection->error;}*/