Article

Beginning Databases with PostgreSQL - Chapter 15: Accessing PostgreSQL from PHP

Page: 1 2 3 4 5 6 7 8 9 10 11 12 Next

Executing Queries

Once the query string has been constructed, the next step is to execute it. Queries are executed using the pg_exec() function.

pg_exec()

The pg_exec() function is responsible for sending the query string to the PostgreSQL server and returning the resultset.

Here's a simple example to illustrate the use of pg_exec():

<?php      
$db_handle = pg_connect("dbname=bpsimple");      
$query = 'SELECT * FROM customer'      
$result = pg_exec($db_handle, $query);      
pg_close($db_handle);      
?>

As you can see, pg_exec() requires two parameters: an active connection handle and a query string. You should already be familiar with each of these from the previous sections. pg_exec() will return a resultset upon successful execution of the query. We will work with resultsets in the next section.

If the query should fail, or if the connection handle is invalid, pg_exec() will return false. It is therefore prudent to test the return value of pg_exec() so that you can detect such failures.

The following example includes some result checking:

<?php      
$db_handle = pg_connect("dbname=bpsimple");      
$query = "SELECT * FROM customer";      
$result = pg_exec($db_handle, $query);      
if ($result) {      
   echo "The query executed successfully.<br>\n";      
} else {      
   echo "The query failed with the following error:<br>\n";      
   echo pg_errormessage($db_handle);      
}      
pg_close($db_handle);      
?>

In this example, we test the return value of pg_exec(). If it is not false (in other words it has a value), $result represents a resultset. Otherwise, if $result is false, we know that an error has occurred. We can then use the pg_errormessage() function to print a descriptive message for that error. We will cover error messages in more detail later in this chapter.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links