05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8 CHAPTER 8<br />

Databases<br />

<strong>PHP</strong> has support for over 20 databases, including the most popular commercial and<br />

open source varieties. Relational database systems such as MySQL, PostgreSQL, and<br />

Oracle are the backbone of most modern dynamic web sites. In these are stored<br />

shopping-cart information, purchase histories, product reviews, user information,<br />

credit-card numbers, and sometimes even web pages themselves.<br />

This chapter covers how to access databases from <strong>PHP</strong>. We focus on the PEAR DB<br />

system, which lets you use the same functions to access any database, rather than on<br />

the myriad database-specific extensions. In this chapter, you’ll learn how to fetch<br />

data from the database, how to store data in the database, and how to handle errors.<br />

We finish with a sample application that shows how to put various database techniques<br />

into action.<br />

This book cannot go into all the details of creating web database applications with<br />

<strong>PHP</strong>. For a more in-depth look at the <strong>PHP</strong>/MySQL combination, see Web Database<br />

Applications with <strong>PHP</strong> and MySQL, by Hugh Williams and David Lane (O’Reilly).<br />

Using <strong>PHP</strong> to Access a Database<br />

There are two ways to access databases from <strong>PHP</strong>. One is to use a database-specific<br />

extension; the other is to use the database-independent PEAR DB library. There are<br />

advantages and disadvantages to each approach.<br />

If you use a database-specific extension, your code is intimately tied to the database<br />

you’re using. The MySQL extension’s function names, parameters, error handling,<br />

and so on are completely different from those of the other database extensions. If<br />

you want to move your database from MySQL to PostgreSQL, it will involve significant<br />

changes to your code. The PEAR DB, on the other hand, hides the database-specific<br />

functions from you; moving between database systems can be as simple as<br />

changing one line of your program.<br />

The portability of an abstraction layer like PEAR’s DB library comes at a price. Features<br />

that are specific to a particular database (for example, finding the value of an<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

189

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!