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

by Yang Yang on July 30, 2010

in PHP Tips & Tutorials

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
}

Related Posts

Leave a Comment

Previous post:

Next post: