SQL Injection!

Beware of SQL Injection attack. If you build your SQL query like that:

$sql = "select * from friend WHERE id = $args[id]";
$ret = $db->query($sql);

an attacker may inject SQL into this id parameter. What does it mean?

Imagine the following request:

http://localhost:8080/friends/2 OR 3 ORDER BY id DESC

The real query that will be executed in the database, will be

select * from friend WHERE id = 2 OR 3 ORDER BY id DESC

which is insanely different from what developer meant! This is a huge security hole in any application if an attacker may modify the query. The example above returns data of an user that the attacker may not have access to.

In order to prevent such situations, ALWAYS take proper care of the data received from the user. In PHP, you should use prepared statements, i.e.:

$sql = "select * from friend WHERE id = :id";
$stmt = $db->prepare($sql);
$stmt->bindValue('id', $args['id']);
$ret = $stmt->execute();

The PHP will take care of proper escaping of the values from the user, so the database engine will not treat them as the part of the query syntax, no matter how nasty they are.

See SQL Injection.

And related XKCD :-)

SQL Injection XKCD