Created
November 1, 2012 00:45
-
-
Save itafroma/3990924 to your computer and use it in GitHub Desktop.
Prepared statements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Don't do this | |
$name = 'Mark'; | |
$query = "UPDATE users SET name = '" . $name . "' WHERE user_id = 1"; | |
$pdo->query($query); | |
// Translates to the query UPDATE users SET name = "Mark" WHERE user_id = 1 | |
// so what's the problem? | |
// | |
// What if we did this instead: | |
$name = "Robert'); DROP TABLE users;--"; | |
$query = "UPDATE users SET name = '" . $name . "' WHERE user_id = 1"; | |
$pdo->query($query); | |
// This would translate to the query: | |
// UPDATE users SET name = "Robert'); DROP TABLE users; -- WHERE user_id =1 | |
// Basically, completely deleting user users table. That would be A Bad Thing. | |
// | |
// Instead, if you prepare the statement beforehand: | |
$query = 'UPDATE users SET name = :name WHERE user_id = 1'; | |
$pdo->prepare($query); | |
$pdo->execute(array(':name' => $name)); | |
// Your query would look something like this: | |
// UPDATE users SET name = '<safely escaped version of $name' WHERE user_id = 1 | |
// Preventing anyone from providing a name that would run a malicious query. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment