PEAR DB Basics
Example 8-1 is a program to build an HTML table of
information about James Bond movies. It demonstrates how to use the
PEAR DB library (which comes with PHP) to
connect to a database, issue queries,
check for errors, and transform the results of queries into HTML. The
library is
object-oriented, with a mixture of
class methods
(DB::connect( )
,
DB::iserror( )
) and object methods
($db->query( )
, $q->fetchInto( )
).
Example 8-1. Display movie information
<html><head><title>Bond Movies</title></head> <body> <table border=1> <tr><th>Movie</th><th>Year</th><th>Actor</th></tr> <?php // connect require_once('DB.php'); $db = DB::connect("mysql://bondview:007@localhost/webdb"); if (DB::iserror($db)) { die($db->getMessage( )); } // issue the query $sql = "SELECT movies.title,movies.year,actors.name FROM movies,actors WHERE movies.actor=actors.id ORDER BY movies.year ASC"; $q = $db->query($sql); if (DB::iserror($q)) { die($q->getMessage( )); } // generate the table while ($q->fetchInto($row)) { ?> <tr><td><?= $row[0] ?></td> <td><?= $row[1] ?></td> <td><?= $row[2] ?></td> </tr> <?php } ?>
The output of Example 8-1 is shown in Figure 8-1.
Figure 8-1. The movie page
Data Source Names
A data source name (DSN) is a string that specifies where the database is located, what kind of database it is, the username and password to use when connecting to the database, and more. The ...
Get Programming PHP now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.