Does codeigniter $this->db->query() or $this->db->escape() prevent SQL Injection?

前端 未结 2 1530
南旧
南旧 2021-01-24 18:45

I want to ask about these 2 method $this->db->escape() and $this->db->query()

Do those can prevent SQL Injection?

2条回答
  •  隐瞒了意图╮
    2021-01-24 19:28

    By default query() does not have any injection prevention methods unless you are using binds.

    $this->db->query("SELECT * FROM sometable WHERE column1 = '?'", array($this->input->post('someitem')));
    

    However, if you use query builder: get(), insert(), and update() as well any of the other query builder methods pass the incoming data through a function that among other things, escapes the data.

    At face value, escaping the data is part of preventing SQL injection, and the other part is prepared queries (which with traditional php is accomplished using PDO and prepared statements). As query builder carries most of the load for you I wouldn't worry about that too much.

    In CI you are safe doing:

    $item = $this->input->post('someitem');
    
    $this->db->insert('sometable', array('column1' => $item));
    

    The insert function will escape $item automatically.

    You can also do XSS cleaning of the post via $item = $this->input->post('someitem', TRUE);

    However you should escape your gets/posts if you are going directly into query()

    $item = $this->input->post('someitem');
    
    $item_esc = $this->db->escape_str($item);
    
    $this->db->query("INSERT INTO `sometable` (`column1`) VALUES ('{$item_esc}')");
    

提交回复
热议问题