How to prevent SQL injection in PHP

How to prevent SQL-injection in PHP,many of you are using core php to built, large and scalable applications in Web.And, you face SQL Injection attacks many times after deploying the application.This tutorial is all about How to prevent SQL injection in PHP in simple steps.
The hacker will use prepared statements and parameterized queries to do his magic trick.We have to prevent the use of prepared statements and parameterized queries, in to our database system.

There are basically two options to prevent SQL Injection in PHP.
1.) Using PHP Data Objects
2.) Using MySQLi ove MySQL

Setup the connection Correctly

An example for creating a connection using PDO, safely for accessing MySQL:

Must obey things:
The first thing should do set up the setAttribute() line.setAttribute() will disable the emulated prepared statements and only use real prepared statements.By doing this, the hacker cannot inject malicious code to SQL.What this actually do is, it makes sure that, the values ans statements are not parsed by PHP before sending this to SQL Server.
Also, setting char set in the options of constructor is possible.

PDO Usage:

MySQLi Usage:

Leave a Reply

Your email address will not be published. Required fields are marked *