Failure to Preserve SQL Query Structure SQL injection is a problem that I see many new members have issues with simply because they do not know about it, or the ways to protect against it. If you do not know what SQL injection is, I suggest reading about it real quick before continuing: [
en.wikipedia.org...]
There are really two ways of approaching the prevention of such attacks, so I will start with the easiest first, character escaping. In PHP this is now done with mysql_real_escape_string() (opposed to mysql_escape_string which does NOT account for the database character encoding). Simply put, you must escape your query parameters before you add them to the query. Example:
$query = sprintf("SELECT * FROM Users where UserName='%s' and Password='%s'",
mysql_real_escape_string($Username),
mysql_real_escape_string($Password));
mysql_query($query);
Taken from the wikipedia page because I'm lazy You can see here that before the parameters are part of the query string, they are escapes of "bad characters" that could have potentially been used in a SQL injection, but most of the time it is common to have those characters in there and they are part of regular user input, but they still must be escaped to correctly work.
The second method to protect against this is to use parameterized or prepared statements. This is the act of binding query parameters to variables. This makes the query string static so that it cannot be injected. With PHP this is commonly done with the PDO database layer or the MySQLi extension. An example of the latter is here:
$db = new mysqli("localhost", "user", "pass", "database");
$stmt = $db -> prepare("SELECT priv FROM testUsers WHERE username=? AND password=?");
$stmt -> bind_param("ss", $user, $pass);
$stmt -> execute();
Taken from the wikipedia page because I'm lazy As a note, this step should always be taken after validating the user input as in my first post. This is layered security here. The more passes at validation and escaping the variable goes through, the less chance that something
dirty got through and will cause problems for you down the road.
[edited by: eelixduppy at 2:47 pm (utc) on Mar 4, 2010]