PHP
  Home arrow PHP arrow Page 7 - Accessing Databases with DB
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Accessing Databases with DB
By: David Sklar
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 13
    2004-11-30


    Table of Contents:
  • Accessing Databases with DB
  • Introducing DSNs
  • Understanding Quoting and Placeholders
  • Examining Data Retrieval Convenience Methods
  • Understanding Query Information
  • Running a Query Multiple Times
  • Introducing Sequences

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Accessing Databases with DB - Introducing Sequences
    ( Page 7 of 7 )

    A sequence is a source of unique integer identifiers. When you need an ID for an item in your database, ask a sequence for its next available ID. This ID is guaranteed to be unique within the sequence. If two queries ask the same sequence for an ID at the same time, each query gets a different answer.

    The easiest way to use a sequence is just to call the DB::nextID() method. This creates the specified sequence if it doesn’t already exist and returns the next available ID in the sequence:

    $flavor_id = $dbh->nextID('flavors');
    $dbh->query('INSERT INTO ice_cream (id,flavor) VALUES
          (?,?)', array($flavor_id,'Walnut'));

    To create sequences explicitly, use createSequence():

    $dbh->createSequence('flavors');

    If you are creating your sequences with createSequence(), you can tell nextID() not to create sequences automatically by passing false as a second argument:

    $flavor_id = $dbh->nextID('flavors',false);
    if (DB::isError($flavor_id)) { 
         die("Can't get sequence ID");
    }
    $dbh->query('INSERT INTO ice_cream (id,flavor) VALUES 
          (?,?)', array($flavor_id,'Walnut'));

    Whether they are created automatically by nextID() or explicitly with createSequence(), the dropSequence() method deletes a sequence:

    $dbh->dropSequence('flavors');

    Introducing Error Handling

    DB methods return a DB_Error object if they fail. The DB_Error object contains fields that describe the error condition. The “Sending Queries and Receiving Results” section describes the basic use of DB::isError(). This function returns true when the object passed to it is a DB_Error object. To comprehensively catch errors with this test, use it each time you call a DB method that may return an error:

    $dbh = DB::Connect('mysql://user:pwd@localhost/dbname');
    if (DB::isError($dbh)) { 
         die("Can't connect: ".$dbh->getMessage());
    }
    $sth = $dbh->query('SELECT flavor,price FROM ice_cream');
    if (DB::isError($dbh)) {
         die("Can't SELECT: ".$sth->getMessage());
    }
    while($res = $sth->fetchRow()) {
         if (DB::isError($res)) {
              die("Can't get row: ".$res->getMessage());
         }
         print "Flavor: $res[0], Price: $res[1]";
    }

    Instead of testing each call to DB::isError() with if(), you can use the and logical operator instead, which is slightly more concise:

    $dbh = DB::Connect('mysql://test:@localhost/test');
    DB::isError($dbh) and die("Can't connect: "
        .$dbh->getMessage());
    $sth = $dbh->query('SELECT flavor,price FROM ice_cream');
    DB::isError($sth) and die("Can't SELECT: "
        .$sth->getMessage());
    while($res = $sth->fetchRow()) {
         DB::isError($res) and die("Can't get row: "
             .$res->getMessage());
         print "Flavor: $res[0], Price: $res[1]\n";
    }

    Still, using DB::isError() after each relevant method call is cumbersome and error prone. If you forget to check the results of one method and it fails, subsequent operations won’t work properly. The DB::setErrorHandling() method allows you to tell DB to automatically take an action whenever a DB method call returns an error. To print the error and exit the program immediately, pass the constant PEAR_ERROR_DIE to setErrorHandling():

    $dbh = DB::Connect('mysql://test:@localhost/test');
    DB::isError($dbh) and die($dbh->getMessage());
    $dbh->setErrorHandling(PEAR_ERROR_DIE);
    $sth = $dbh->query('SELECT flavor,price FROM ice_cream');
    while($res = $sth->fetchRow()) {
         print "Flavor: $res[0], Price: $res[1]\n";
    }

    To print the error but continue program execution, use PEAR_ERROR_PRINT instead of PEAR_ERROR_DIE. You can also use setErrorHandling() to have a custom function called each time there’s a DB error. Pass PEAR_ERROR_CALLBACK as the first argument to setErrorHandling() and the name of the function to call as the second argument:

    $dbh = DB::Connect('mysql://test:@localhost/test');
    DB::isError($dbh) and die($dbh->getMessage());
    $dbh->setErrorHandling(PEAR_ERROR_CALLBACK,'db_error');
    $sth = $dbh->query('SELECT flavor_name,price FROM
           ice_cream');
    while($res = $sth->fetchRow()) {
         print "Flavor: $res[0], Price: $res[1]\n";
    }
    function db_error($err_obj) {
         print "Error! [$err_obj->code] $err_obj->userinfo";
    }

    Because this example has an unknown field in the SQL query (flavor_name instead of flavor), the db_error() error callback is called, and it prints this:

    Error! [-19] SELECT flavor_name,price FROM ice_cream
    [nativecode=1054 ** Unknown column 'flavor_name' in
    'field list']

    Error callbacks are useful for queries inside of a transaction. If there’s an error, the callback can automatically roll back the transaction and print a message or return the proper value to indicate that the transaction failed. 

    This chapter is from Essential PHP Modules, Extensions, Tools, by David Sklar (Apress, 2004, ISBN: 1590592808). Check it out at your favorite bookstore today.

    Buy this book now.



     
     
    >>> More PHP Articles          >>> More By David Sklar
     

       

    PHP ARTICLES

    - Using Directory Iterators to Build Loader Ap...
    - Using the spl_autoload() Functions to Build ...
    - Working Out of the Object Context to Build L...
    - Using the _autoload() Magic Function to Buil...
    - The Destruct Magic Function in PHP 5
    - The Autoload Magic Function in PHP 5
    - Developing a Recursive Loading Class for Loa...
    - The Sleep and Wakeup Magic Functions in PHP 5
    - Using the Clone Magic Function in PHP 5
    - Including Files Recursively with Loader Appl...
    - The Call Magic Function in PHP 5
    - Designing a Captcha System with PHP and MySQL
    - Using Static Methods to Build Loader Apps in...
    - The Isset and Unset Magic Functions in PHP 5
    - Advanced PHP Form Input Validation to Check ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT