• Martin Thoma
  • Home
  • Categories
  • Tags
  • Archives
  • Support me

PHP: PEAR MDB2

Contents

  • PHP: PEAR MDB2
    • Install PEAR
    • Install PEAR MDB2
    • Usage
    • Sources

PEAR is short for PHP Extension and Application Repository. It provides a very easy method to get some common classes.

PEAR MDB2 is a database class. It is a successor of PEAR DB. I took a look at version 1.4.1 which is currently the latest stable one.

Install PEAR

You can install PEAR on Ubuntu via

sudo apt-get install php-pear

You can check if it is installed with phpinfo():

<?php phpinfo();?>

Something like .:/usr/share/php:/usr/share/pear should be in your include_path.

Install PEAR MDB2

PEAR MDB2 is then simply installed via

sudo pear install MDB2

Then install the optional MySQL package:

sudo pear install pear/MDB2#mysql

Usage

I took a small chess database to test this package. You can set it up with this sql file.

It's sad, but only including MDB2.php shows 5 "Deprecated"-messages and 6 warings because of "Strict Standards".

You can easily connect to the database:

require_once "MDB2.php";

$db   = new MDB2();
$dsn  = "mysql://chessuser:[email protected]/chess";
$mdb2 = MDB2::factory($dsn);
$mdb2->setFetchMode(MDB2_FETCHMODE_ASSOC);

It is also very easy to fetch some data:

$sql    = 'SELECT * FROM `chess_users`';
$result = $mdb2->query($sql);
while ($row = $result->fetchRow()) {
    print_r($row);
}

or

$sql    = 'SELECT * FROM `chess_users`';
$data = $mdb2->queryAll($sql);
print_r($data);

This results in:

Array
(
    [user_id] => 1
    [user_name] => abc
    [user_password] => 900150983cd24fb0d6963f7d28e17f72
    [currentchesssoftware] => 0
)
Array
(
    [user_id] => 2
    [user_name] => test
    [user_password] => 098f6bcd4621d373cade4e832627b4f6
    [currentchesssoftware] => 0
)

You can set limits via MDB2:

$sql    = 'SELECT * FROM `chess_users`';
$mdb2->setLimit(1);
$data = $mdb2->queryAll($sql);
print_r($data);

MDB2 offers lots of other features like choosing a (non)persistent connection, prepared statements or debuggin option. If you're interested in PEAR MDB2 I recommend to take a look at installationwiki.org.

Sources

  • PEAR. Received 24 September 2011.
  • PEAR MDB2. Received 24 September 2011.
  • MDB2 on installationwiki.org. Received 24 September 2011.

Published

Sep 24, 2011
by Martin Thoma

Category

Code

Tags

  • Database 6
  • PEAR 1
  • PHP 9
  • Web Development 14

Contact

  • Martin Thoma - A blog about Code, the Web and Cyberculture
  • E-mail subscription
  • RSS-Feed
  • Privacy/Datenschutzerklärung
  • Impressum
  • Powered by Pelican. Theme: Elegant by Talha Mansoor