Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for database connection, otherwise display message

I would like to check if the website can connect to mySQL. If not, I would like to display an error saying that the user should try to access the page again in a few minutes...

I really do not know how to do this ;)

Any help would be greatly appreciated!

string mysql_error ([ resource $link_identifier ] )

But how do I use this?

This just gives me the error, but I want the message to display with any error.

Thanks

like image 476
Chriswede Avatar asked Jan 26 '12 22:01

Chriswede


People also ask

What does it mean when a website says error establishing a database connection?

This error means that your website files (on the webserver) are not able to connect to your database (on the database server). This article lists some common reasons this error could display on your site, including: Incorrect database credentials in your config file. The hostname isn't working.


2 Answers

Try this:

<?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";
?>
like image 137
psyklopz Avatar answered Oct 13 '22 00:10

psyklopz


very basic:

<?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');
?>

result:

Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'user'@'localhost' (using password: YES) in /home/user/public_html/zdel1.php on line 6 try again in some minutes, please

as per Wrikken's recommendation below, check out a complete error handler for more complex, efficient and elegant solutions: http://www.php.net/manual/en/function.set-error-handler.php

like image 35
tony gil Avatar answered Oct 12 '22 23:10

tony gil