SQL Injection
SQL injection is used to try and
insert a MySQL statement to be run on your database without your knowledge.
Injection usually occurs when you ask a user for input, like their name or username,
and instead of a name they give you a MySQL statement that you will unknowingly run
on your database.
Examples of what can happen
Help Avoid it
There is a built in function named mysql_real_escape_string() which will protect us.
What mysql_real_escape_string() does is take a string that you want to used in a MySQL query and return the same string with all SQL Injection attempts safely escaped so thy don't affect.
I like to make up a function that I can call when accessing the database and got used to using it in any database call. I stick it in a functions file that I use on lots of sites. I call the function cleanSQL and here it is:
<?php
function cleanSQL($text){
$text=stripslashes($text);
if (!is_numeric($text)) $text = "'" . mysql_real_escape_string($text) . "'";
return $text;
}// End cleanSQL
?>
To use:
$sql = sprintf("SELECT * FROM table WHERE username=%s",cleanSQL($username));
$result = mysql_query($sql);