Languages
[Edit]
EN

PHP - how to prevent SQL injection?

17 points
Created by:
Wiktor-Sribiew
830

Web development requires to guarant safety of application. Really serious problem is to prevent against SQL Injection Attack. This kind of attack is based on typing SQL sub querry in value place of main query. One way to prevent of this kind of attack is to escape some dangerous charactes from values. PHP provaids special API that helps to solve this problem. In this article simple solutions how to prevent the attack has been shown.

1. PDO class example

Edit

In this example solution how to use :role agrument to prevent SQL Injection has been shown. With this approach all dangerous characters that are sent inside role argument are escaped as safe text and paced into SQL query.

Result:

SQL Injection prevention with PDO class - PHP / MySQL.
SQL Injection prevention with PDO class - PHP / MySQL.

2. MySQLi example

Edit

In this example bind_param function has been used with question mark inside SQL query to escape all dangerous characters.

Result:

SQL Injection prevention with mysqli class - PHP / MySQL.
SQL Injection prevention with mysqli class - PHP / MySQL.

3. mysql_real_escape_string function example

Edit

Note: this approach is marked as depricated since PHP 5.5.0 and removed sice PHP 7.0.0. 

Result:

SQL Injection prevention with mysql_real_escape_string function - PHP / MySQL.
SQL Injection prevention with mysql_real_escape_string function - PHP / MySQL.

4. Database preparation

Edit

create_tables.sql file:

insert_data.sql file:

See also

Edit
  1. PHP - how to make MySQL insert query with PDO?
  2. PHP - how to make MySQL select query with PDO?
  3. PHP - how to make MySQL update query with PDO?
  4. PHP - how to make MySQL delete query with PDO?

 

1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join