Forum Moderators: coopster
above approach is free of SQL injection but has tedious job of writing mysql_real_escape_string() for every field values.
I would like to know the good approach for auto escaping,so that i don't have to write those escaping manually.
I have seen some styles like:
1>
[PHP]$sql = "SELECT * FROM table WHERE field1='%s' AND field2 ='%s'";
$result = custom_query($sql, array($field1_value, $field2_value));[/PHP]
2>
[PHP]$sql = "SELECT * FROM table WHERE field1=? AND field2 =?"; //without using quotes which will be auto detected & quoted accordingly
$result = custom_query($sql, array($field1_value, $field2_value));[/PHP]
Note: above doesn't uses prepared statement.
what will the custom_query() function look like ?
anybody has used similar function?
Thanks in advance for the valueable suggestion.
so, with that in mind, i'd do the following:
$inputs = array('field1_value', 'field2_value');
foreach ($inputs as $item) {
$$item = mysql_real_escape_string($item);
}
$sql = "SELECT * FROM table WHERE field1='$field1_value' AND field2 ='$field2_value'";
if you're taking post/get values, then change the foreach to:
$$item = mysql_real_escape_string($_POST['item']);
and if you want to go further with this, then build a custom mysql_real_escape_string function. fwiw, mine is:
function safe_input($t="") {
// use forward look up to convert & and not {
$t = preg_replace("/&(?!#[0-9]+;)/s", '&', $t );
$t = str_replace( "<", "<" , $t );
$t = str_replace( ">", ">" , $t );
$t = str_replace( '"', """, $t );
$t = str_replace( "'", ''', $t );
$t = str_replace( "í", ''', $t );
$t = str_replace( "ñ", '-', $t );
$t = str_replace( " ", ' ', $t );
// clean bad stuff
$t = preg_replace( "/javascript/i" , "javascript", $t );
$t = preg_replace( "/alert/i" , "alert" , $t );
$t = preg_replace( "/about:/i" , "about:" , $t );
$t = preg_replace( "/onmouseover/i", "onmouseover" , $t );
$t = preg_replace( "/onclick/i" , "onclick" , $t );
$t = preg_replace( "/onload/i" , "onload" , $t );
$t = preg_replace( "/onsubmit/i" , "onsubmit" , $t );
$t = preg_replace( "/<body/i" , "<body" , $t );
$t = preg_replace( "/<html/i" , "<html" , $t );
$t = preg_replace( "/document\./i" , "document." , $t );
return trim($t);
}
[edited by: eelixduppy at 8:50 pm (utc) on Jan. 19, 2010]
[edit reason] disabled smileys [/edit]