This is a dumping ground for examples ..
Here's one of the most basic examples of how to get MDB2 running in no time:
require_once 'MDB2.php';
$dsn = 'mysql://user:pass@host/db';
$mdb2 =& MDB2::factory($dsn);
if (PEAR::isError($mdb2)) {
echo ($mdb2->getMessage().' - '.$mdb2->getUserinfo());
}
$query ='SELECT * FROM test';
// run the query and get a result handler
$result = $mdb2->query($query);
// check if the query was executed properly
if (PEAR::isError($result)) {
echo ($result->getMessage().' - '.$result->getUserinfo());
exit();
}
// lets just get row:0 and free the result
$array = $result->fetchRow();
$result->free();
var_dump($array);
Here is the example.php that comes with MDB2:
http://cvs.php.net/co.php/pear/MDB2/docs/examples/example.php?view=markup
And another one that uses some PHP5 specific features:
http://cvs.php.net/co.php/pear/MDB2/docs/examples/example_php5.php?view=markup
MDB2 2.0.0beta3 will support the following mechanism to automatically either use native autoincrement or native sequences:
$mdb2->loadModule('Extended');
// fetch the next ID in the sequence or return php null
$id = $mdb2->extended->getBeforeID('foo');
$query = 'INSERT INTO foo (id, bar) VALUES ('.$id.', '.$mdb2->quote('xxx', 'text').')';
$mdb2->exec($query);
// return $id or fetch the last inserted id via autoincrement
$id = $mdb2->extended->getAfterID($id, 'foo');
Furthermore you can use the lastInsertID() method to either get the last generated autoincrement ID or to get the current value of a sequence:
$query = 'INSERT INTO foo (id, bar) VALUES (NULL, '.$mdb2->quote('xxx', 'text').')';
$mdb2->exec($query);
// fetch the last inserted id via autoincrement or current value of a sequence
// note the name of the sequence is derived as follows:
// $seq = $table.(empty($field) ? '' : '_'.$field);
$id = $mdb2->lastInsertID($table, $field);
// NOTE: the lastInsertID method ONLY WORKS when connection mode is FACTORY