Go to content Go to navigation Go to search

PHP MDB2 Quick Guide

The basics


require_once 'MDB2.php';

// normally want just a single connection instance
$db =& MDB2::singleton('pgsql://user:pwd@server/dbname');

// for autoExecute, MDB2_AUTOQUERY, limitQuery, etc
$db->loadModule('Extended');

$db->escape( $s );

// core selects
$db->queryAll('SELECT * FROM people');
$db->queryRow('SELECT * FROM people WHERE id = 1');
$db->queryCol('SELECT name FROM people');

// using Extended module
$db->getOne()
$db->getRow()
$db->getCol()
$db->getAll()
$db->getAssoc()


// MDB2 "types" are different from PHP types 'text' => '', 'boolean' => true, 'integer' => 0, 'decimal' => 0.0, 'float' => 0.0, 'timestamp' => '1970-01-01 00:00:00', 'time' => '00:00:00', 'date' => '1970-01-01', 'clob' => '', 'blob' => '', )

Transaction blocks


if ($mdb2->supports('transactions')) { $mdb2->beginTransaction();

}
$result = $mdb2->query('DELETE people');
if (PEAR::isError($result)) {

if ($mdb2->in_transaction) { $mdb2->rollback(); // echo 'rollback'; }
} else { if ($mdb2->in_transaction) { $mdb2->commit(); // echo 'commit'; }
}

Extras


// to allow empty strings
$mdb2->setOption( 'portability', MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_EMPTY_TO_NULL
);

Alternatively, get higher level and check out symfony

Previous post:
Ruby performance notes
Next post:
Ubuntu Server Setup Edgy to Feisty