how to avoid sql injection in codeigniter
CodeIgniter's Active Record methods automatically escape queries for you, to prevent sql injection.
$this->db->select('*')->from('tablename')->where('var', $val1);
$this->db->get();
or
$this->db->insert('tablename', array('var1'=>$val1, 'var2'=>$val2));
If you don't want to use Active Records, you can use query bindings to prevent against injection.
$sql = 'SELECT * FROM tablename WHERE var = ?';
$this->db->query($sql, array($val1));
Or for inserting you can use the insert_string()
method.
$sql = $this->db->insert_string('tablename', array('var1'=>$val1, 'var2'=>$val2));
$this->db->query($sql);
There is also the escape()
method if you prefer to run your own queries.
$val1 = $this->db->escape($val1);
$this->db->query("SELECT * FROM tablename WHERE var=$val1");
you can use
$this->db->escape()
method..
$sql = "INSERT INTO table (title) VALUES(".$this->db->escape($omgomg).")";
other methods are listed here.
http://codeigniter.com/user_guide/database/queries.html
You should try to avoid writing your queries directly into a string and then passing them to the query function. A better option would be to use the Active Record class which will build your queries for you and escape the values. http://codeigniter.com/user_guide/database/active_record.html
If you want to avoid using the Active Record class for whatever reason then you can view the Codeigniter documentation for the database class which has an escape method for escaping your values before passing them to the query method. http://www.codeignitor.com/user_guide/database/queries.html
Ben
While accepting value from client side, Better to use this code,
$client = $this->input->post('client',TRUE);
While inserting better to use codeigniter inserting method,
$this->db->insert('tablename',$values);
When using this method codeingniter automatically do all escape so we no need do escape manual.