Simple technique to avoid the SQL injection in PHP

Before we go to discuss the techniques, We should known what is SQL injection?

SQL injection:

SQL injection is one of the attack in which vulnerable code is inserted into strings that are later passed to an instance of SQL Server for parsing and execution.


There are two ways to avoid the SQL injection.

  • Use prepared statements or parameterized queries
  • Use escape in input string

Use prepared statements or parameterized queries:  It is one of the way to process the input data by SQL server seprately . This way it is impossible for an attacker to inject malicious SQL.

For example:

By Using PDO:

 By Using Mysqli:

Use escape in input string : It is another way to avoid SQL injection. Whenever you use dynamic values in your query then you must escape it before use it in your query.

When you inject some expected integer value into an SQL query, make sure it’s an integer,by  using intval().

When you have a decimal/numeric field in your table, use  floatval().

And when you have a string (char, varchar, text) field in your table, use the function provided by your API to escape strings :




Please don’t forget to share and subscribe to latest updates of the blog.

  • john

    Useful one….