SQL injection

How to Prevent SQL Injection in PHP

To prevent SQL injection, you have two options:

1. Using PDO to Prevent SQL

Using PDO (for any supported database driver): PDO is an acronym for PHP Data Objects. This is a consistent way to access databases.

$stmt = $conn->prepare("SELECT * FROM items WHERE category =:categ");
	$stmt->execute(array(':categ' => $categ));

 foreach ($stmt as $row) {
     // Do something with $row

2. Using MySQLi to Prevent SQL

 $stmt = $conn->prepare('SELECT * FROM items WHERE category = ?');
 $stmt->bind_param('s', $categ); 


 $result = $stmt->get_result();
 while ($row = $result->fetch_assoc()) {
     // Do something with $row

SQL injection refers to a code injection technique used to attack data-driven applications, in which malicious SQL statements are inserted into an entry field for execution. It allows an intruder to interfere with queries made to a database. With SQL injection, an intruder ends up manipulating your database in such ways like deleting even viewing restricted data. This greatly compromises the integrity and security of your database. You can imagine the kind of mess this would imply to anyone’s compromised data. Imagine of a situation where an intruder accesses a bank’s database and clears all loans!! To start with, the management will start by hanging you as the database manager before they close their bank. This makes greatly important for you to learn how to prevent SQL injection as a crucial part of data security.

Avoiding SQL Injection

The best way in which to avoid SQL injection attack is to separate the data from SQL. This works for you no matter the database you are going to use. What does it mean to separate data from SQL? It implies that, your data remains as data and no longer interpreted as commands by the SQL parser. If you can, create SQL statement with correctly formatted data parts. However, if you are not comfortable with that, just use the prepared statement and parameterized queries.


Prepared Statement and Parameterized Queries

Prepared statement and parameterized queries refer to SQL statements sent to and parsed by the database server separately from any parameters. This make it practically impossible for an attacker to inject malicious SQL hence making your data secure.

Related Posts


Get the Facebook Likebox Slider Pro for WordPress