Checking Database Connections and Getting Errors in PHP
We have talked about how to make database connections in PHP before. However, I realized that I have forgotten something which is so important. If you read that article or you are interested in PHP, you may know that we use odbc_connect() or mysql_connect() (or etc.) functions to connect some databases. These functions try to connect to specified databases. I wish every request would be accepted, because it is possible getting errors during the process. If the connection is not successful, the rest of codes will not work properly. So today, I will show you how to check database connections.
It is so simple checking database connections in PHP. We need to know that connection functions like mysql_connect, odbc_connect, pg_connect, fbsql_connect etc. returns false, if connection is not successful. So this is an advantage for us because, we can define conditions to test connections like that:
I. Checking Just Database Connections
Method 1.0: Checking database connections without getting errors.
As you see, if we specify the connection_id as a condition we can test our connections. In Method 1.0, if there is no error that means if $ConnectionName or $DatabaseConnection is not false then operations is executed.
II. Checking Database Connections and Getting Connection Errors
This time, we want to write the error messages. To detect exactly which error occurred, we need to know which database is used. Because, functions that return error messages, are specified according to databases in PHP.
2.1) Reporting MySQL Errors
Method 2.0: Checking MYSQL database connections and getting errors.
mysql_errno() function returns error code of error. mysql_error() function retrieves the error text. You don’t have to specify the connection_id in functions. If no connection is found or established, an E_WARNING level error is generated.
2.2) Reporting MSSQL, MDB, XLS Errors
We use odbc_connect() function to connect to MSSQL, MDB, XLS etc. databases. So odbc_ functions can be used for these databases, and we use odbc_error() and odbc_errormsg() to report errors. odbc_error() gets the last error code and odbc_errormsg() gets the last error message.
Method 2.1: Checking MSSQL database connections and getting errors.
2.2) All Error Functions for All Databases in PHP
There is a list of all database drivers exist in PHP. You can find and use other database functions and whatever you need. Database Extentions in PHP.
Conclusion
I tried to show you basics of testing connections. Examples may not be coded properly, but that’s not my point, and I think this is enough for us. You can write your questions, additions or criticisms as a comment. I would like to answer them.

You may wrap your connection command into try-catch block and just display exception.