Categories
PHP Tips & Tutorials

How to check if a MySQL database connection is successful in PHP?

If you have mysqli extension installed with PHP and you use it to perform database operations, after you have tried to connect to MySQL by:

$conn = new mysqli('localhost', 'db_user', 'db_pwd', 'db_name');

You can then check if the connection is successful by:

if ($conn -> connect_errno) {
  // failure
} else {
  // success
}

That’s because connect_errno contains the error number of the last query. If there’s no error, it’s 0 by default. If an error occurred in the last query, it’s a natural number greater than zero. There you go with the conditional check of whether the PHP database connection is successful.

However if you are using the legacy mysql extension to connect to MySQL databases:

$conn = mysql_connect('localhost', 'db_user', 'db_pwd');

It’s even simpler. The returned value of mysql_connect() function will be FALSE should the connection fail. Therefore, you can check if the connection is successful by:

if ($conn = mysql_connect('localhost', 'db_user', 'db_pwd')) {
  // success
} else {
  // failure
}

By Yang Yang

Hello, I'm Yang. I build online businesses that please people. Want to join in and post some useful articles on Kavoir.com? Shoot me a message.