how to avoid sql injection in codeigniter

前端 未结 6 1997

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:



        
6条回答
  •  一生所求
    2020-11-29 20:01

    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");
    

提交回复
热议问题