MyBB Community Forums

Full Version: Bulletproof Database Access
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I've read a number of books on PHP over the years, and almost all of them make the same mistakes when it comes to database access. Applications that use SQL improperly are susceptible to SQL injection attacks, which can literally hand your entire database (and its contents) over to the hackers. What's even worse, is that the proper way to do database access is actually easier than the improper way.

To illustrate, the example below shows proper SQL command construction.

<?php
require_once("DB.php");
$dsn = 'mysql://root:password@locahost/posts'
$db =& DB::Connect($dsn, array());
if(PEAR::isError($db)) { die($db->getMessage()); }

$sth = $db->prepare("INSERT into posts VALUES ( null, ? )" );
$db->execute($sth, array( $_POST['post'] ) );
?>

I used the PEAR DB module to prepare a statement, with the ? placed where the arguments are to go. Some in the PHP community suggest that PEAR DB is slower. I haven't experienced that; and even if that were the case, I would still use PEAR DB because it provides portability and security features that the direct database access functions do not.

A new alternative to PEAR DB is on the horizon as well; it's the PHP Database Objects (PDO) library. It's currently experimental, but its worth monitoring in the long term as an alternative to PEAR DB.
PDO isn't really experimental at the moment as it is now included in newer releases of PHP.

We'll possibly move to PDO in the future as it matures more.