Sql Injection

SQL injection errors occur when:
1. Data enters a program from an untrusted source.
2. The data is used to dynamically construct a SQL query.

Example 1: The following code dynamically constructs and executes a SQL query that searches for items matching a specified name. The query restricts the items displayed to those where the owner matches the user name of the currently-authenticated user.

$userName = $_POST['userName'];
$itemName = $_POST['itemName'];
$query = "SELECT * FROM items WHERE owner = '$userName' AND itemname = '$itemName';";
$result = mysql_query($query);

If an attacker with the user name enters the string “name’ OR 1=1 for itemName, then the query becomes the following:
SELECT * FROM items WHERE owner = ‘John’ AND itemname = ‘name’ OR 1=1;
The addition of the OR 1=1 condition causes the where clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:
SELECT * FROM items;

Example 2. If an attacker with the user name wiley enters the string “name’; DELETE FROM items; –” for itemName, then the query becomes the following two queries:
SELECT * FROM items WHERE owner = ‘John’ AND itemname = ‘name’; DELETE FROM items;

Recommendations:
(1) use mysql_real_escape_string function when we get the value from form.
eg.

$username= mysql_real_escape_string($_POST['userName']);
$itemName= mysql_real_escape_string($_POST['itemName']);

(2) use sql pdo query not simple query

$query = "SELECT * FROM items WHERE owner = ? AND itemname = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param($username,$itemName);
$stmt->execute();