The DB.php file defines a class of type DB. Refer to Chapter 5 for more information on working with classes and objects. We'll principally be calling the methods in the class. The DB class has a connect method, which we'll use instead of our old connect function mysql_connect. The double colons (::) indicate that we're calling that function from the class in line 4: connection = DB::connect("mysql://$db_username:$db_password@$db_host/$db_database"); When you call the connect function, it creates a new database connection that is stored in the variable $connection. The connect function attempts to connect to the database based on the connect string you passed to it. Connect string The connect string uses this new format to represent the login information that you already supplied in separate fields: dbtype://username:password@host/database This format may look familiar to you, as it's very similar to the connect string for a Windows share. The first part of the string is what really sets the PEAR functions apart from the plain PHP. The phptype field specifies the type of database to connect. Supported databases include ibase, msql, mssql, mysql, oci8, odbc, pgsql, and sybase. All that's required for your PHP page to work with a different type of database is changing the phptype! The username , password, host, and database should be familiar from the basic PHP connect. Only the type of connection is required. However, you'll usually want to specify all fields. After the values from dblogin.php are included, the connect string looks like the following: "mysql://test:test@localhost/test" If the connect method on line 6 was successful, a $DB object is created. It contains the methods to access the database as well as all of the information about the state of that database connection. Querying One of the methods it contains is called query. The query method works just like PHP's query function in that it takes a SQL statement. The difference is the hyphen and greater-than syntax (->) is used to call it from the object. It also returns the results as another object instead of a result set. $query = "SELECT * FROM `books`" Based on the SQL query, this code calls the query function from the connection object and returns a result object named $result. Fetching Line 22 uses the result object to call the fetchRow method. It returns the rows one at a time, similar to mysql_fetch_row. while ($result_row = $result->fetchRow()) { You use another while loop to go through each row from fetchRow until it returns FALSE. The code in the loop hasn't changed from the non-PEAR example. Closing In line 30, you're finished with the database connection, so you close it using the object method disconnect: $connection->disconnect(); |
|
|
|
|
|
|
|