[Solved] Protecting PHP against MySQL injections [duplicate]


As you’re in your own words a noob there’s no time like the present to pick up some good habits 🙂

$email = $_POST['email'];
$sql="INSERT INTO users (email) VALUES ('$email')";

is a textbook example of an SQL injection vulnerability, and this code will bite you sooner or later. The reason is that you trust the variable you receive, and hand it over to the SQL engine. Just imagine what happens if someone enters

'); drop table users; --

as their email address…

Instead of devising all kinds of sophisticated schemes to clean up the input, there’s one ironclad technique that makes your code immune against injection attacks: prepared statements. As you should not start developing the deprecated mysql_ calls offered by php, you should switch to PDO or mysqli_. I would suggest PDO, which supports prepared statements. More about prepared statements here. Using PDO and prepared statments, your sample will look like this:

$stmt = $dbh->prepare("INSERT INTO users (email) VALUES (:email)");
$stmt->bindParam(':email', $email);
$stmt->execute();

You will have future proof code that’s ready to be used with other database systems than MySQL and that’s immune to injection attacks.

solved Protecting PHP against MySQL injections [duplicate]