如何避免codeigniter中的sql注入 [英] how to avoid sql injection in codeigniter
问题描述
在 CodeIgniter 中,如何避免 sql 注入?有没有什么方法可以在配置文件中设置以避免sql注入?我正在使用此代码来选择值:
In CodeIgniter, how can I avoid sql injection? Is there any method to set in config file to avoid sql injection? I am using this code for selecting values:
$this->db->query("SELECT * FROM tablename WHERE var='$val1'");
这用于插入值:
$this->db->query("INSERT INTO tablename (`var1`,`var2`) VALUES ('$val1','$val2')");
另一种用于从数据库中插入和选择值的方法是 CodeIgniter 的 insert()
和 get()
方法.使用CodeIgniter的内置函数时是否有机会进行sql注入
Another method used to insert and select values from the database is CodeIgniter's insert()
and get()
methods. Is any chance to sql injection while using CodeIgniter's bulit-in functions
推荐答案
CodeIgniter 的 Active Record 方法会自动为您转义查询,以防止 sql 注入.
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();
或
$this->db->insert('tablename', array('var1'=>$val1, 'var2'=>$val2));
如果你不想使用 Active Records,你可以使用 查询绑定 防止注射.
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));
或者对于插入,您可以使用 insert_string()
方法.
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);
还有 escape()
方法,如果您更喜欢运行自己的查询.
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");
这篇关于如何避免codeigniter中的sql注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!