Monday, November 10, 2008

there are so many options with pear's db library for php, I sometimes forget the optimal code for getting a sql result as an array that I can easily use within php. The code below fully demonstrates connecting to and getting an associative array with an 'order by' field as the array key. This code is for a postgres rdms, but could easily be modified for mysql, sqlserver, etc. Parameters are in caps surrounded by '%' in the form %PARAMETER%.

require_once 'DB.php';

$dsn = "pgsql://%LOGIN%:%PASSWORD%@%HOST%/%DBNAME%";
$dbh =& DB::connect ($dsn);
if (PEAR::isError($dbh)) {
die($dbh->getMessage());
}

$dbh->setFetchMode(DB_FETCHMODE_ASSOC);
$res =& $dbh->getAssoc('%SQL STATEMENT, USE 'ORDER BY' TO DEFINE ARRAY KEY%');

if (PEAR::isError($res)) {
die($res->getMessage());
}

No comments: