Friday, September 19, 2008

Introduction to PEAR

PEAR, the PHP Extension and Application Repository, is a bountiful resource for any PHP developer. Within its confines lie the tools that you need to do your job more quickly and efficiently. You need to be able to quickly assess and determine which PEAR package is the right one for the task you are up against. Then you need to know the API and see some examples of how to best use it.
Now PHP is continuously moving towards its heights. If you love oops, you will love PHP5 and of course PEAR.
I am giving the simple example of using PEAR::DB package:
 // Include the pear class
require_once("DB.php");
$dsn=array(
'phptype'  =>'mysql',
'hostspec' => 'localhost',
'database' => 'test_db',
'username' => 'test_user',
'password' => 'test_password'
);
$dbh = DB::connect($dsn);

$stmt = "SELECT id, name FROM examples ORDER BY id";
$result = $dbh->simpleQuery($stmt, DB_FETCHMODE_ASSOC);
if ($dbh->numRows($result) > 0) {
$data = (object) $dbh->fetchRow($result, DB_FETCHMODE_ASSOC);
echo "id => $data->id
\n";
echo "name => $data->name
\n";
}

Using that package, we don't need to think of the database server we are using, we only need to pass an array as shown above to the static function connect(), it will make connection to the database server that can be MySQL, PostgreSQL, and Oracle.

To use PEAR, you have to install PEAR. To install PEAR and know about available packages, the URL is pear.php.net
We will continue with these series, till then enjoy and live programming.

No comments: