Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter this->db->query

Does $this-db->query() have mysql injection protection? I was wondering because I use this in instances and have not done anything to protect against sql injection.

like image 409
Michael Grigsby Avatar asked Dec 27 '22 16:12

Michael Grigsby


2 Answers

The ActiveRecord style of querying with CodeIgniter escapes parameters, but not query().

You can use active record in this manner:

$someAge = 25;
$this->db->select('names, age');
$query = $this->db->get_where('people', array('age' => '>' . $someAge));

Read more about it here: https://www.codeigniter.com/userguide2/database/active_record.html

like image 53
Steve Avatar answered Jan 04 '23 20:01

Steve


No, db->query() is not SQL Injection protected by default, you got few options. Use Query Bindings

$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?"; 
$this->db->query($sql, array(3, 'live', 'Rick'));

For more complex quires where you have to build the query as you go on, use compile_bind() to get chunk of SQL.

$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?"; 
$safe_sql  = $this->db->compile_bind($sql, array(3, 'live', 'Rick'));

etc.

Or use escape $this->db->escape() on parameters

$sql = "INSERT INTO table (title) VALUES(".$this->db->escape($title).")";

It's always best practise to use form validation first and include things like xss_clear, max_length etc either way in combination with one of the above.

like image 45
xelber Avatar answered Jan 04 '23 22:01

xelber