Forum Moderators: coopster
I've never really considered this until recently, but after reading more about it, I'd like some advice on how to do it.
Most of the articles on it I read weren't particularly helpful or detailed, so I thought I would ask here in hopes of getting a simple answer.
I've been able to protect numeric values by using is_numeric and failing if false, but I'm still lost as to how to prevent SQL injection on strings.
IE in the following code (I know it's bad, just trying to give a simple example from my head)
$username = addslashes($_POST['username']);
$id = '4';
mysql_query("UPDATE table_test SET
username=$username
WHERE ID=$id");
--
I been told it's possible to inject SQL into that statement and similar statements, but I've no idea how to protect against it.
I'd apreciate any advice.
$username = addslashes($username);
$id = intval($id);
mysql_query("UPDATE table_test SET username='$username' WHERE ID='$id'");
;)
After reading a lot of that, following links, and reading more, and double checking the PHP documentation itself and it's comments, I'm still unsure on when to use addslashes, and when to use mysql_real_escape_string?
When do you use which, and why?
Thanks a lot.
Quote each non numeric user supplied value that is passed to the database with the database-specific string escape function (e.g. mysql_escape_string(), sql_escape_string(), etc.). If a database-specific string escape mechanism is not available, the addslashes() and str_replace() functions may be useful (depending on database type).
Kind of limits you if you are designing an application that you may want to port to other databases though. If you intend to port in this way, you should use your own abstraction layer or the PEAR::DB class.
Although I had read mysql_real_escape_string was preferred, addslashes is normally what tends to be recommended, so I wondered if there was anything it did that mysql_real_escape_string did not, and if it was preferable in any particular circumstances (other than working with different database systems)
Thanks.
function fix_for_mysql($value){
if (get_magic_quotes_gpc()) $value = stripslashes($value);
$value = "'" . mysql_real_escape_string($value) . "'";
return $value;
}
Then, since it already has the single quotes around it, I use it like this:
$username = fix_for_mysql($username);
$q = sprintf("select password from users where username = %s", $username);
$result = mysql_query($q, $dbc);