How to prevent SQL injection in PHP

What is SQL injection?

In simple terms, SQL injection is simply a person trying to maneuver your SQL queries by sending in SQL commands through input fields provided to them at the users' end. In PHP, this can be done by sending these commands through the user registration form or comment form. In this shot, we will see how to prevent SQL injection in PHP.

How to prevent SQL in PHP

To ensure we have a secured website that is not vulnerable to SQL injection, we have to make sure the connection to our database is very secured.

How do we ensure a secured connection to the SQL database?

We will use the php pdo to create our connection like so:

<?php
$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4', 'root', '');
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Explanation

  • Line 2: We initiate a connection to our database using php pdo.

Note: Here, we're assuming that you know how to setup connection to your SQL database using pdo, and the script above is just to improve security.

  • Line 4: We must know what is happening on line 4 in the above script. It does almost all of the SQL injection prevention, inside the setAttribute() method, which tells PDO to use actual prepared statements while disabling emulated prepared statements. This gives no opportunity to an attacker to inject malicious SQL commands.
  • Line 5: We handle all possible exceptions.

Free Resources