How to use pear In PHP to connect to MySQL

Last updated on January 27th, 2022 at 12:44 pm

Click to rate this tutorial!
[Total: 0 Average: 0]

PEAR is PHP Extension and Application Repository. This is a very simple example that uses a Database connection using pear which is an application repository in PHP.

Create a Database of your choice and run these sql queries in the database.

CREATE TABLE mydb_test (
  mydb_test_id mediumint(9) NOT NULL auto_increment,
  mydb_test_stamp bigint(20),
  mydb_test_text varchar(50),
  PRIMARY KEY (mydb_test_id)
);
INSERT INTO mydb_test VALUES (1,783173,'My Data For Today');
INSERT INTO mydb_test VALUES (2,731637,'My Data For Tmrw');
INSERT INTO mydb_test VALUES (3,873612,'Day After');

Now our PHP file for connecting to the database and displaying the data from the db using PEAR.

Install db module using https://pear.php.net/package/DB

pear install DB

Here is the complete code.

<?php
require_once('DB.php');
$dbhost = 'localhost';
$dbuser = '<YOUR_DB_USERNAME>';
$dbpass = '<your_db_password>';
$dbname = 'YOUR_DB_NAME';
//Here i am using MYSQL as the DB, You are flexible to use any DB like Plsql, Db2 etc by simply changing the below code assigned to variable $db, This is the main advantage of using PEAR.
$db = DB::connect("mysql://$dbuser:[email protected]$dbhost/$dbname");
// no need to select DB like our conventional method
if (PEAR::isError($db)) {
die($db->getMessage());
}
$sql = 'SELECT * FROM mydb_test';
 
$demoResult = $db->query($sql);
while ($demoRow = $demoResult->fetchRow()) {
    echo $demoRow[2] . '<br />';
}
$db->disconnect();
?>
Click to rate this tutorial!
[Total: 0 Average: 0]

Leave a Reply

Your email address will not be published.