PEAR DB Extension

While developing an application, most of us use MySQL database as the backend. There might come scenarios when we might need to change the Database system to something else like MaxDB / PostgreSQL / SQLServer /anything else.

Had we used many mysql realted functions in our PHP scripts, it would be difficult to hunt them down and make the neccessary changes, even if the SQL statements involved are going to change. Think, changing every mysql_query(), mysql_fetch_array(), mysql_blabla into maxdb_query() and so on. How hard would it be. I believe most of us would not want to be into such tricky situations. There are simple solutions for these.

PHP Pear packages offer ready made simple solutions, for many of the basic needs. And PEAR DB Extension, is one of most used.
The PEAR DB is a set of classes that provides you with :

  • Database abstraction
  • Advanced Error Handling
  • and more..
Check out this : How to install PEAR and PEAR::DB Extension

Let us discuss how can we use PEAR::DB in our PHP applications.

require_once 'DB.php';
The above statement has to be included in all the files where class is used. Note : The PEAR base directory has to be set in your include_path.

Connecting and Disconnecting from a database

$user = 'foo';
$pass = 'bar';
$host = 'localhost';
$db_name = 'clients_db';

// Data Source Name: This is the universal connection string
$dsn = "mysql://$user:$pass@$host/$db_name";
$db = DB::connect($dsn);

// Disconnect
$db->disconnect();

Querying and Fetching Rows from the Database

$sql = "select * from clients";
$result = $db->query($sql); // Querying the Database
while ($row = $result->fetchRow()) {
// Result row
$id = $row[0];
}




Quick data Retrieval

$numrows = $db->getOne('select count(id) from clients');
// getOne retrieves the first result of the first column from a query

$row = $db->getRow($sql)
// getRow will fetch the first row and return it as an array

$all_client_names = $db->getCol('select name from clients');
// getCol will return an array with the data of the selected column. It accepts the column number to retrieve as the second param.


For much more details about this please goto : http://vulcanonet.com/soft/?pack=pear_tut

It is simple.. Right?

Enjoy.

Posted byShyam at 4:02 PM  

1 comments:

Thanjeys said... Saturday, May 26, 2007  

Hai shyam..
Your content very helpful for us.. But You also Publish lot of php contents..

Post a Comment