PEAR's core components are general-purpose, reliable packages that work with most web servers, database servers, browsers, and operating systems. If you're using PHP 4.3 or later on a Unix system, the PEAR core components and the PEAR installer for adding other packages are already installed and ready for use. For Microsoft Windows, the integration occurred in PHP 4.3.2. The list of core components can change but at the time of writing it includes:
7.2.1 What's Installed?Now, let's check the core components distributed with your PHP installation. 7.2.1.1 Unix systems PHP 4.3.0 and laterFor the instructions in this section to work, you must have followed our installation instructions in Appendix A to Appendix C. You also need an active Internet connection. To check the list of components installed, you need to login as the root user; to do this, type su at a shell prompt and provide the root user password. If you're working with Mac OS X, type at a shell prompt: % cd /usr/local/bin Then, on all systems, type the following at a shell prompt: % pear list You'll see a list in the following format: Installed packages: =================== +------------------+---------+--------+ | Package | Version | State | | Archive_Tar | 0.9 | stable | | Console_Getopt | 1.0 | stable | | DB | 1.3 | stable | | HTTP | 1.2 | stable | | Mail | 1.0.1 | stable | | Net_SMTP | 1.0 | stable | | Net_Socket | 1.0.1 | stable | | PEAR | 1.0b3 | stable | | XML_Parser | 1.0 | stable | | XML_RPC | 1.0.4 | stable | You may find that the versions you have are different. This isn't a problem. 7.2.1.2 Microsoft Windows PHP 4.3.2 and laterFor the instructions in this section to work, you must have followed our installation instructions in Appendix A to Appendix C. You also need an active Internet connection. Start by launching a command window. You can do this by running the file command.com or running a DOS prompt window (if it's listed in your Accessories group under Programs in your Start Menu). To run command.com, click on the Start Menu, then the Run option. Now, type command.com and press Enter. In your command window, change directory to the pear install directory. If you've followed our install instructions in Appendix A to Appendix C, type: C:\> cd c:\Progra~1\EasyPH~1\php\pear Then, type the following: C:\> pear.bat list A list of installed packages is shown in the following format: INSTALLED PACKAGES: =================== PACKAGE VERSION STATE Archive_Tar 0.9 stable Console_Getopt 1.0 stable DB 1.3 stable HTTP 1.2 stable Mail 1.0.1 stable Net_SMTP 1.0 stable Net_Socket 1.0.1 stable PEAR 1.0b3 stable XML_Parser 1.0 stable XML_RPC 1.0.4 stable You may find that the versions you have are different. This isn't a problem. If you want to close the command window, type exit. However, you'll need this window later in this chapter, so keeping it open is fine. 7.2.2 Using PEAR DBIn most PHP applications, one of the server-specific database libraries is used to access the database server. In Chapter 6, we showed you how to access the MySQL sever using the MySQL library functions. In this section, we show you how to develop reasonably server-independent scripts using PEAR's DB component. We also use the PEAR DB class throughout our online winestore in Chapter 16 through Chapter 20. 7.2.2.1 Should I use PEAR DB?If you want server-independent function calls, PEAR's DB component is ideal because the code usually doesn't change when you change the underlying database server. However, there are sometimes needs for small changes, such as catering for different function return values or rewriting code because a database server doesn't support a feature. For example, only some of the underlying servers support the tableInfo( ) method for returning metadata about table attributes. If you don't use PEAR DB, changing database servers can be time-consuming. If you switch between similar libraries such as the MySQL and PostgreSQL libraries then updating the code usually doesn't require too much work: it's largely a case of changing the mysql_ prefix to a pgsql_ prefix, and perhaps tackling complex querying in a different way. However, if you change to a less-similar library such as one of the Oracle libraries or ODBC then more work is required even for the simple tasks. PEAR DB will almost give you function library independence, but it won't give you complete database server independence. SQL isn't the same between any two servers: as we discussed in Chapter 1, combinations of the features of SQL-89, SQL-92, and SQL-99 are often implemented, and many servers have proprietary statements for tasks. For example, MySQL supports entry-level SQL-92, but uses proprietary clauses such as LIMIT and AUTO_INCREMENT, and attribute types such as LONGINT and TIMESTAMP. Even if you use PEAR DB, it's almost impossible (and probably not sensible) to avoid using proprietary SQL. For many developers, it isn't clear whether database abstraction offers an advantage: many developers don't bother writing server-independent code because their SQL is tied to the database server. In fact, if you're sure you'll be using one database server for the lifetime of an application, we recommend using the proprietary library so that you can take advantage of the specialized functions designed for the database server. In most of the applications we've developed, we've used the MySQL library functions outlined in Chapter 6. However, to illustrate how to use PEAR DB and to give you code that will work with minimal modification for other database servers, we've used it to develop our online winestore in Chapter 16 through Chapter 20. 7.2.2.2 Getting startedIn this section, we assume you've read Chapter 6 and are familiar with the basic querying processes and the core MySQL library functions. Also, you'll need to be familiar with the basic object-oriented PHP features discussed in Chapter 4. Example 7-1 shows how to connect, query, and retrieve results using PEAR DB. The example is an extended version of Example 6-1 that includes error handling. Example 7-1. Using PEAR DB to query the winestore database<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html401/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Wines</title> </head> <body><pre> <?php require_once "DB.php"; require "db.inc"; $dsn = "mysql://{$username}:{$password}@{$hostName}/{$databaseName}"; // Open a connection to the DBMS $connection = DB::connect($dsn); if (DB::isError($connection)) die($connection->getMessage( )); // (Run the query on the winestore through the connection $result = $connection->query("SELECT * FROM wine"); if (DB::isError($result)) die ($result->getMessage( )); // While there are still rows in the result set, fetch the current // row into the array $row while ($row = $result->fetchRow(DB_FETCHMODE_ASSOC)) { // Print out each element in $row, that is, print the values of // the attributes foreach ($row as $attribute) print "{$attribute} "; print "\n"; } ?> </pre> </body> </html> As discussed previously, there's no need to download or install any extra components to use the PEAR core components. The PEAR DB class is used within a script by requiring it: require_once "DB.php"; If you find that your PHP engine can't find DB.php, it's likely that your include_path directive in your php.ini configuration file doesn't include the PEAR directory. Check the installation instructions for your platform in Appendix A to Appendix C. Connecting to a database server uses a URL-style string. In the example, this string consists of the familiar $username, $password, $hostName, and $databaseName from the db.inc require file: $dsn = "mysql://{$username}:{$password}@{$hostName}/{$databaseName}"; For the defaults in the db.inc file, this gives the string: mysql://fred:shhh@localhost/winestore We store the string in a variable with the acronym $dsn to signify this is the data source name . The prefix mysql:// indicates the MySQL server, and the string fred:shhh@localhost specifies the username, password, and host parameters that are used with the mysql_connect( ) and mysql_pconnect( ) functions. Rather than use the separate mysql_select_db( ) function to use the database, it's specified following a forward slash character. The connection itself is established with the method DB::connect( ) : $connection = DB::connect($dsn); The notation DB:: means that the method connect( ) is a member of the class DB. Error handling is discussed in the next section. The DB::query( ) method works similarly to mysql_query( ), taking the SQL query as a parameter and returning a result resource that can be used to retrieve data from a SELECT query: $result = $connection->query("SELECT * FROM wine"); The result rows are retrieved using the DB::fetchRow( ) method: while ($row = $result->fetchRow(DB_FETCHMODE_ASSOC)) The method behaves similarly to mysql_fetch_array( ). The parameter DB_FETCHMODE_ASSOC specifies that the return array has associatively-accessible elements that are named with the database attribute names or attribute aliases; however, this isn't important in this example because we use foreach to iteratively process all elements of the array. 7.2.2.3 Handling errors in PEAR DBThe error status of any database server method can be tested using DB::isError( ) . Unlike in the MySQL library, this method can be used regardless of whether a connection has been established yet or not. If an error occurs, the getMessage( ) method can be used to retrieve a descriptive string as in the following example: // Open a connection to the DBMS $connection = DB::connect($dsn); if (DB::isError($connection)) die($connection->getMessage( )); The getMessage( ) method is part of the core PEAR error class. The method works similarly for testing errors from queries: $result = $connection->query("SELECT * FROM wine"); if (DB::isError($result)) die ($result->getMessage( )); Note that the method can be used with many types of objects: for connections, we use the $connection object and for results we use $result. If a method or parameter is unsupported by the underlying database server, you'll find that the following error is reported: DB_error: database not capable 7.2.2.4 Essential functions for accessing MySQL with PEAR DBMethods for interacting with database servers using PEAR DB are the subject of this section. We've included the essential methods, and omitted those that are less-frequently used, redundant, or aren't used with MySQL. More detail on all methods can be found in the PEAR manual at http://pear.php.net/manual/en/core.db.php. For most PEAR DB methods, we've noted which native MySQL functions are used in the library to implement the functionality that's described. Chapter 6 presents the detail of the underlying MySQL functions, and you'll find that the limitations and advantages of those functions affects PEAR DB too. We recommend reading the MySQL function notes in conjunction with the PEAR DB descriptions.
|