Now, in PHP5, you have Pear::DB, Zend_DB, PDO, mysqli, and mysql API in interacting with that MySQL database. However, all speed tests show that mysql API is the fastest except when doing prepared SQL statements. For prepared SQL statements, mysqli API is the fastest. So, since I don't use mysqli-type prepared statements, I use the straight mysql API.
Wrapping that API is very important to me. It lets me swap databases or control a problem from a central place. I stick it in a $db class and I have methods like Run, RunFast, GetRows, GetRowFromRows, GetNextRow, GetRowCount, GetColCount, Translate (builds a simple SELECT statement on the fly), and so on.
After working on enough projects, no one likes find a project where the SQL is sprayed all over the place. So, you'll find my SQL in a single class file with public variables storing parameterized SQL statements where ^ is the symbol I use to indicate where a value would go. I call it like so:
require_once('DB.php'); //this already instantiates the $db object for me in the class file
$sSQL = $settings->SQL_GET_USERS_BY_LASTNAME;
$db->Pack($sSQL, 'Smith');
$rsRows = $db->GetRows($sSQL);
while ($db->GetNextRow($rwRow, $rsRows)) {
echo $rwRow['email'] . "<BR>\n";
}
$db->Release($rwRow);
$db->Release($rsRows);
And in my $settings class, you'll see something like:
$this->SQL_GET_USERS_BY_LASTNAME = "
SELECT
*
FROM
users
WHERE
disabled = 0
AND lastname = '^'
ORDER BY
firstname;
";
See how much cleaner it is to use this sort of technique?
[EDIT: See my post on July 9, 2008 where this is superceded.]
No comments:
Post a Comment