How do I check if I'm connected to database?

31,919

Solution 1

Do it Like this

if ($con) {
  echo 'connected';
} else {
  echo 'not connected';
}

Or try this

echo $con ? 'connected' : 'not connected';

Solution 2

Firstly, use the mysqli_xxx() functions instead of the old obsolete mysql_xx() functions.

This is strongly recommended anyway because the old library is in the process of being deprecated, but will also make your question easier to answer. (you could also use the PDO library, for which the answer will be similar, but for this answer I'll stick with mysqli for simplicity)

With the mysqli library, you get a variable that contains your DB connection, which you can examine at any point.

$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

Now, you can query the $mysqli variable to find out what is happening.

if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}

Later on, you can query the variable using the ping command: http://www.php.net/manual/en/mysqli.ping.php

$mysqli->ping();

or maybe the stat command if you want more info: http://www.php.net/manual/en/mysqli.stat.php

Share:
31,919
lisovaccaro
Author by

lisovaccaro

Updated on May 22, 2020

Comments

  • lisovaccaro
    lisovaccaro almost 4 years

    This is the code to connect to the mysql database:

    $con = mysql_connect("", "", "");
    
    if (!$con) {
      die('Could not connect: ' . mysql_error());
    }
    
    mysql_select_db("", $con);
    

    I want to echo 'connected'/'disconnected' depending on state.

    How can it be done?

  • lisovaccaro
    lisovaccaro over 11 years
    I'm trying to use Mysqli but I've been unable to go past an error connecting. Do most servers support mysqli? I'm using mediatemple. Thanks
  • Spudley
    Spudley over 11 years
    @Liso22 - I know very little about mediatemplate, but mysqli is a standard part of PHP and has been for a long time. It's also been recommended in preference to the older mysql library for a long time too, so I can't imagine any PHP systems of any quality not supporting it.
  • Alvin K.
    Alvin K. about 10 years
    Update: With PHP 5.5 onwards, use mysqli_ping()