Home / How to escape variables with PHP PEAR DB

How to escape variables with PHP PEAR DB

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)) {
$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.