Check for database connection, otherwise display message

Chriswede picture Chriswede · Jan 26, 2012 · Viewed 148.7k times · Source

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

Answer

psyklopz picture psyklopz · Jan 26, 2012

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";
?>