Development Wiki

Dbal.sql escape

From phpBB Development Wiki

dbal::sql_escape –– Escapes special characters in a string for use in a SQL statement.


string dbal::sql_escape ( string $msg )

This function is used to create a legal SQL string that you can use in an SQL statement. The given string is encoded to an escaped SQL string. Always use $db->sql_escape() if you need to check for a string within an SQL statement (even if you are sure the variable cannot contain single quotes - never trust your input). Using this function ensures proper sanitisation and prevents any possible SQL Injection from the input variable.


Parameter Usage
msg The string to be escaped. Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", Control-Z and DBAL specific SQL escape characters.

Return Values

Returns an escaped string.


Example #1 Usage Example

$username request_var('username''');

$sql 'SELECT *
    FROM ' 
    WHERE username = '" 
$db->sql_escape($username) . "'";

Example #2 Vulnerable SQL Statement

This query will fail, because we didn't escape $city
This is an example of an SQL Injection

$city "'s Hertogenbosch";

$sql 'SELECT state
        FROM ' 
        WHERE city = '
$result $db->sql_query($sql);

Example #3 Already escaped queries

In this example, the $db->sql_build_array() method already escapes strings used on the input, so using $db->sql_escape is not needed in this instance.

$sql_ary = array(
'city'  => $city,
'state' => $state,

$sql 'INSERT INTO ' MY_TABLE ' ' $db->sql_build_array('INSERT'$sql_ary);

See Also