简体   繁体   中英

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

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?

Do it Like this

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

Or try this

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

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

Try using mysql_ping

mysql_ping — Ping a server connection or reconnect if there is no connection

something like this should help you

if(mysql_ping($con)) 
  echo 'connected'; 
 else 
  echo 'disconnected';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM