There\'s a lot of warnings about SQL injections here on SO, but no one I\'ve found doesn\'t really answer, how does it happen? In this question, I\'m assumi
Source: http://xkcd.com/327/
This will not work with mysql and php without deliberate steps to make it possible, since the normal query function will only execute the first query.
That doesn't mean it's not possible - only that it should be very obvious when it is.
But the above means almost nothing in terms of sql injection. There is a huge, huge amount of information out there about sql injection including a large number of questions here on stack overflow. Taking the example in the question, this is an equivalent attack which would work:
$id = "123 OR 1 = 1 --";
mysqli_query($con,"DELETE FROM table WHERE id = $id LIMIT 1");
i.e. finding an interface to delete my own, e.g., comment, if the id is not escaped it would be trivial to delete all comments. But this example is just the very tip of an iceberg.
This code in the question:
$stm = $pdo->prepare("INSERT INTO table (Column) VALUES ('$unsafe')");
$stm->execute();
Has none of the benefits of using PDO - i.e. any exploit (of the truly massive number) that would work with the mysql/mysqli driver (used naively) will work with pdo used in this way.
Using PDO with prepared statements with parameters escapes values appropriately preventing sql injection attacks, so yes this is safe from injection:
$stm = $pdo->prepare("INSERT INTO table (Column) VALUES (?)");
$stm->execute(array($unsafe));
Simply by finding a way to execute sql that either does what they want to do, or gives them the information to do it a different way.
For example:
function login() {
$username = "irrelevant' OR is_admin = 1 --";
$password = hash('irrelevant');
$query = "SELECT id from users where username = '$username' AND password = '$password'";
...
}
How did malicious user get access to the admin functionality on a system with no concern for injection? Very easily.
For general information about injection see the previous references.