PDO - Using Prepared Statements to Stop Injection Attacks

Using prepared statements, sometimes also known as parametrized queries, helps prevent SQL Injection Attacks.

<?php
 
// Do some validation first!
if (filter_var($_GET['int_col'], FILTER_VALIDATE_INT) === false) {
  die('You must enter a valid integer!');
}
 
$dsn = 'mysql:dbname=my_database;host=myserver.com';
$username = 'username';
$password = 'password';
$user_id = 1;
 
// Set up PDO.
$pdo = new PDO($dsn, $username, $password);
 
// Our parametrized query using placeholders.  No need for quotes around values, it will do this for us.
$query = "SELECT secret_data FROM mytable WHERE string_col = ? AND int_col = ? AND user_id = ?";
 
// Our input values in order for the place holders.  No need to escape, it will do it for us!
$parameters = array($_GET['string_col'], $_GET['int_col'], $user_id);
 
// Prepare the query.
$statement = $pdo->prepare($query);
 
// Execute the query with our parameters
$statement->execute($parameters);
 
// Get the first returned row.
$row = $statement->fetch(PDO::FETCH_ASSOC);
 
?>