Skip to content

How to Prevent SQL injection in Codeigniter?

In the web application security, SQL injections are place a very important role. To prevent SQL injections in PHP, we usually use mysql_real_escape_string() function along with other techniques.

In codeIgniter ,we no need to use mysql_real_escape_string() function, Codeigniter provides inbuilt functions and libraries to generate SQL queries by using those methods or functions we can avoid SQL injections.

There are three methods to prevent SQL injections in Codeigniter application, they are
1) Escaping Queries
2) Query Binding
3) Active Record Class

Preventing SQL injection in Codeigniter using Escaping Query Method

Example:

input->post('email'); 
   $query = 'SELECT * FROM subscribers_tbl WHERE user_name='.$this->db->escape($email); 
   $this->db->query($query); 
?>

Here $this->db->escape() determines the data type so that it can escape only string data.
It also automatically adds single quotes around the data so you don’t have to do that as well.

Preventing SQL injection in Codeigniter using Query Binding Method

db->query($sql, array('active', '[email protected]'));
?>

The question marks in the query are automatically replaced with the values in the array in the second parameter of the query function.

in Query Binding Method, you don’t have to escape the values manually as it will automatically do that for you.

Preventing SQL injection in Codeigniter using Active Record Class

Using Active Records, query syntax is generated by each database adapter. It also allows for safer queries, since the values are escaped automatically by the system.

db->get_where('subscribers_tbl',array('status' => 'active','email' => '[email protected]'));
?>
0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments