How to escape variables with PHP PEAR DB
Posted January 25th, 2010 in PHP
When using the PHP PEAR DB database abstraction library it is important to escape variables just as it is when using the native database function calls. If you don't know why this is then do a search using your favourite search engine for "sql injection". This post shows the PEAR DB way of escaping variables.
escapeSimple() function
The PEAR DB escapeSimple() function is used to escape strings. It in turn calls the native PHP function to escape the string, such as mysql_real_escape_string() in the case of MySQL.
Here's an example of connecting to the database using PEAR DB and then running a query after escaping the variable, which is done on line 5.
$db = DB::connect($dsn);
if(PEAR::isError($db)) {
die($db->getMessage());
}
$escaped_variable = $db->escapeSimple($unescaped_variable);
$query = "SELECT * FROM sometable WHERE something = '$escaped_variable'";
$result = $db->query($query);
Using bound placeholders
Bound placholders can also be used so you don't have to worry about escaping strings manually and I will look at how to do this in my PHP post next Monday.
Related posts:
- Fetching data using PHP and PDO with bound placeholders (Friday, February 26th 2010)
- How to escape variables with PHP PEAR DB with bound placeholders (Monday, February 1st 2010)
- PHP PEAR DB Code Completion in Zend Studio (Friday, November 2nd 2007)

Comments
blog comments powered by Disqus