When you talk about PHP and databases, people tend to assumeyou're talking about MySQL. But hang on to your horses - difficultthough it may be to believe, PHP does include support for a number ofother databases. One of them is PostgreSQL, the *other* open-sourcedatabase - and this article tells you everything you need to know aboutusing it with PHP.
All done? Nope, not quite yet - before you go out there and start building cool data-driven Web sites for your customers, you should be aware that PHP comes with some powerful error-tracking functions which can speed up development time. Take a look at the following example, which contains a deliberate error in the SELECT query string:
<html>
<head><basefont face="Arial"></head>
<body>
<?
// database access parameters
// alter this as per your configuration
$host = "localhost";
$user = "postgres";
$pass = "postgres";
$db = "test";
// open a connection to the database server
$connection = pg_connect ("host=$host dbname=$db user=$user
password=$pass");
if (!$connection)
{
die("Could not open connection to database server");
}
// generate and execute a query
$query = "SELECTA * FROM addressbook";
$result = pg_query($connection, $query) or die("Error in query: $query.
" . pg_last_error($connection));
// get the number of rows in the resultset
// this is PG-specific
$rows = pg_num_rows($result);
echo "There are currently $rows records in the database";
// close database connection
pg_close($connection);
?>
</body>
</html>
And here's the output:
Warning: pg_query() query failed: ERROR: parser: parse error at or near
"selecta" in /usr/local/apache/htdocs/e.php on line 23 Error in query:
SELECTA * FROM addressbook. ERROR: parser: parse error at or near
"selecta"
The pg_last_error() function displays the last error returned by
PostgreSQL. Turn it on, and you'll find that it can significantly reduce the time you spend fixing bugs.