SQL Injection Mitigation techniques



SQLi Mitigations

However SQL injection has very high impact, its extremely easy to prevent it, and here is the most efficient techniques:

  1. Prepared statements
  2. Escaping user input
  3. Whitelisting input

Prepared statements

Prepared statement is a feature to execute same queries for many times with high efficiency

and here is an example of an insert SQL statement in PHP

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);

// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);

one of the main advantages of prepared statements that its not vulnerable to SQL Injection attacks

Escaping user input

before using user input in our statment it has to be filtered using

for php we use mysqli_real_escape_string() to escape input before putting it in our statment

// ... db connection code ...

// escape firstname,lastname and age
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$age = mysqli_real_escape_string($con, $_POST['age']);

$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";

// executing query and error handling
if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
echo "1 record added";




Ready to be protected?

14 days trial , No credit card upfront , Risk free