phpBB

Development Wiki

Dbal.sql escape

From phpBB Development Wiki

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

Description

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.

Parameters

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.

Examples

Example #1 Usage Example

$username request_var('username''');

$sql 'SELECT *
    FROM ' 
SOME_TABLE "
    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 ' 
MY_TABLE "
        WHERE city = '
$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