The
sql_quote()
function is used to secure or filter data content (with apostrophes) in order to avoid SQL injection attacks. This function is very important and must be used whenever content is provided by user data entry. The
sql_insertq
,
sql_updateq
, and
sql_replace
functions automatically apply this filtering for any inserted data (but not for the other parameters like
$where
which ought to be filtered nonetheless anyway).
It accepts 3 parameters:
-#
$val
is the expression to be filtered,
-#
$serveur
,
-#
$type
optional, is the type of value expected. This would equal
int
for an integer value.
It is used as shown below:
$charstring = sql_quote("David's car");
$fieldname = sql_quote($fieldname);
sql_select('column', 'table', 'titre=' . sql_quote($titre));
sql_updateq('table', array('column'=>'value'), 'titre=' . sql_quote($titre));
Whenever a numeric identifier is expected, which is often the case for primary keys, the filtering may simply apply the PHP
intval()
function (the value zero will be returned if the content passed is not numeric):
$id_table = intval(_request('id_table'));
sql_select('column', 'table', 'id_table=' . intval($id));
Example
The
url_delete()
function deletes URLs from the SQL table that stores the URLs for SPIP editorial objects. It filters the strings using
sql_quote()
and uses
intval()
on the identifier:
function url_delete($objet, $id_objet, $url=""){
$where = array(
"id_objet=" . intval($id_objet),
"type=" . sql_quote($objet)
);
if (strlen($url)) {
$where[] = "url=" . sql_quote($url);
}
sql_delete("spip_urls", $where);
}