Home arrow PHP arrow Page 3 - Databases and PHP

PEAR DB Basics - PHP

If you're interested in learning how to access databases from PHP, you've come to the right place. This four-part series will focus on the PEAR DB system. This article is excerpted from chapter eight of the book Programming PHP, Second Edition, written by Kevin Tatroe, Rasmus Lerdorf, and Peter MacIntyre (O'Reilly, 2006; ISBN: 0596006810). Copyright 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

  1. Databases and PHP
  2. Relational Databases and SQL
  3. PEAR DB Basics
  4. Data Source Names
By: O'Reilly Media
Rating: starstarstarstarstar / 8
June 14, 2007

print this article



Example 8-1 is a program to build an HTML table of information about science fiction books. 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. Be sure to verify how to turn on PEAR with your setup of PHP, as the Unix/Linux flavor is slightly different to that of Windows. Go to http:// www.pear.php.net/manual/en/installation.getting.php for a starting point on installation. 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 book information

<html><head><title>Library Books</title></head>

<table border=1>
<tr><th>Book</th><th>Year Published</th><th>Author</th></tr>
 // connect
$db = DB::connect("mysql://librarian:passw0rd@localhost/ library");
if (DB::iserror($db)) {

 // issue the query
$sql = "SELECT books.title,books.pub_year,authors.name
FROM books, authors
WHERE books.authorid=authors.authorid
ORDER BY books.pub_year ASC";
 $q = $db->query($sql);
 if (DB::iserror($q)) {

 // generate the table
while ($q->fetchInto($row)) {
<tr><td><?= $row[0] ?></td>
    <td><?= $row[1] ?></td>
<td><?= $row[2] ?></td>

The output of Example 8-1 is shown in Figure 8-1.

Figure 8-1.  The Library page

>>> More PHP Articles          >>> More By O'Reilly Media

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: