The FuzzyBlog! : PHP Pear Programming Tutorial The FuzzyBlog!

Marketing 101. Consulting 101. PHP Consulting. Random geeky stuff. I Blog Therefore I Am.

Home FuzzyGroup About Us Our Services

PHP Pear Programming Tutorial

If you haven't worked with the Pear database abstraction class then you really should.   Now I know that everyone says that and we often don't bother – "too hard", "it's a pain", etc.  It's really not.  Here's how I learned how to do it and what I recommend. 

  1. Write a simple PHP app to do nothing more than list the contents of a table using the MySQL native functions.
  2. Go through and convert it line by line to the Pear equivalents.

Our first script should be familiar to anyone who has ever used the basic MySQL functions in PHP.  I'm not going to go into details here since it's so basic.

<?php// //////////////////////////////////////////////////*

My SQL Test Script for Learning Pear

All this does is connect to a MySQL db and list a table

*/// /////////////////////////////////////////////////

// pull from a file $db, $db_host, $db_password, $db_userinclude "zcommondb.php";

  // Connecting, selecting database  $link = mysql_connect("$db_host", "$db_user", "$db_password")    or die("Could not connect");

  //select the database  mysql_select_db("$db")    or die("Could not select database");

// the query  $query = "SELECT * FROM fo2_emails LIMIT 20";

  $result=mysql_query($query)    or die ('<H1 align=center><font color=red>Bad Database Request</font></H2> in :<BR>'      . __FILE__.' line '. __LINE__       .'<BR><br /><b>The query used was:</b><BR><BR> '.$query      .'<BR><br /><b>MySQL says</b><BR><BR> '.mysql_error()      .'<BR><BR>Email administrator for help at ' . $sysadminemail . ' for help' );

  while ($row = mysql_fetch_array($result))  {    //start a counter so that we can keep track of how many records we change      $ctr++;      $email_id = $row["email_id"];      $account_address = $row["accountaddress"];      $subject = $row["subject"];      print "<P>$email_id - $account_address - $subject</P>"; }?>

Contents of the zcommondb.php file are this:


$db_host = "YOUR VALUE HERE"; $db = "YOUR VALUE HERE"; $db_user = "YOUR VALUE HERE"; $db_password = "YOUR VALUE HERE"; // ONLY USED BY THE PEAR ROUTINES $db_type = "mysql";


So that's our starting point. Now here's the pear equivalent.  As you can see it's just about exactly the same number of lines with the main differences being in the use of objects.  I put the new / different code in Red to make it easier.

<?php// //////////////////////////////////////////////////*

My SQL Test Script for Learning Pear

All this does is connect to a MySQL db and list a table

*/// /////////////////////////////////////////////////

  // pull from a file $db, $db_host, $db_password, $db_user  include "zcommondb.php";  require_once "DB.php";

  //NEW STUFF -- Pear specific  //static method to parse the DSN connection string into an array  $dsn = DB::parseDSN("$db_type://$db_user:$db_password@$db_host/$db");

  //static factory method to create an object of $db_type  $db_obj = DB::factory("$db_type");

  //connect to the database and display an error message if it fails  if (!$db_status = $db_obj->connect($dsn)) {    echo "Error: " . $db_status -> message . "<br />";    echo "Code: " . $db_status-> code . "<br />";  }

  // the query  $query = "SELECT email_id, accountaddress, subject FROM fo2_emails LIMIT 20";

  // NEW STUFF -- Pear specific  $result = $db_obj->simpleQuery($query);  while($row = $db_obj->fetchRow($result,DB_FETCHMODE_ASSOC)) {    $ctr++;    $email_id = $row["email_id"];    $account_address = $row["accountaddress"];    $subject = $row["subject"];    print "<P>$email_id - $account_address - $subject</P>";  }?>

As you can see, it really isn't much if at all harder to use Pear than the native mysql_XYZ functions.  Keep that in mind as you write php code. 


How'd He Colorize That ?

If you want to display a colorized source view of your code then make a Unix symbolic link and Apache / PHP will properly colorize the code when it's executed:


ln -s source dest.phps


ln -s example_pear_mysql.php example_pear_mysql.phps

Thanks to Apokalyptik and Natrak who both showed me this over the past six months or so.

addslashes Versus mysql_escape_string

If you're not yet ready to do the pear step then you might want to consider moving away from mysql_escape_string and to addslashes.  These functions seem to be equivalent and yet one will work across databases and one is only MySQL specific.  But I do recommend reading the user contributed notes on addslashes(), it seems to not be perfect.  Guess which one I'm largely using now?

I learned this stuff two ways:

  • Groveling through the Drupal source code [Go]
  • Mastering PHP 4.1 by Sybex which has a short but outstanding section on Pear and Databases [Go]

Thanks to both.  Kudos to Mastering PHP 4.1.  Don't be thrown by the 4.1 nomenclature, it's a surprisingly good book.  They even cover how to decrypt MIME attachments which I couldn't find in a single other PHP book (and I checked like 20 including the table of contents to the forthcoming O'Reilly PHP Cookbook).


There is nothing wrong with the native MySQL php functions but if you have any intent on moving your code to another database then starting with the Pear stuff now is definitely a good thing.  It really isn't hard and it will make you a bit more confident with the PHP object stuff which is increasingly important.


This Page was last update: 4/6/2003; 3:13:59 AM

Copyright 2003 The FuzzyStuff

Theme Design by Bryan Bell

Click here to visit the Radio UserLand website. Subscribe to "The FuzzyBlog!" in Radio UserLand. Click to see the XML version of this web page. Click here to send an email to the editor of this weblog.