How Do You Have PHP Return an Informative Error Message When a SQL Command Returns No Results?

Problem scenario
You have a PHP web page that integrates with Postgres behind the scenes.  You find that when a SQL command returns nothing (e.g., when a table name is used and it is known to not exist in the underlying database), the PHP web page is blank.  You want the result to be more clear about what happened or potentially happened.  How do you handle an exception or commonly occurring SQL query with no results using PHP?  

Solution
This assumes you were using pg_query.  Remember that pg_query returns a boolean value if the query failed.  If credentials were not typed in correctly the result of the pg_query() will be a false.  

Successful pg_query executions will return non-false statements -- but the value will not necessarily be "TRUE."  Failed executions will return false.

The solution is to introduce logic by testing the result of the pg_query() with an if statement.

...
$cc = pg_query($query);
if($cc) {} else {echo  '<td>' . "Query failure.  Did you enter the correct credentials?  Was the relevant table name typed correctly?  Was the user the owner of the database or table involved?  Were certain variables hard-coded that prevent the operation you attempted?" . '</td>';}

Leave a comment

Your email address will not be published. Required fields are marked *