How can we prevent SQL injection in PHP?

How can we prevent SQL injection in PHP?
4.9 (97.78%) 9 votes

Sometime, user input something we dont know and dont want, then our SQL query could becomes vulnerable to SQL injection, for example:

Think twice, what if user input something like this:

Now, our query become:

Do you know what does it mean? 🙂

Now, how can we prevent this from happening?

Use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.

We have 2 simple way to do it:

Using PDO (avaiable in MySQL and MariaDB):

Using MySQLi (for MySQL):

Other way, you can prevent it by remove all special character BEFORE input to query. In the next post, Bien Thuy will help you with class or functions remove all special character before input to query.

Last update: 02:31:13 AM, 23rd December 2017

About Author

Leave A Reply