防止 CodeIgniter 中的 SQL 注入


Prevent SQL Injection in CodeIgniter

CI 活动记录会阻止 SQL 注入吗?

这是我的代码

    $this->db->select('t.DateTime,
                       su.FirstName,
                       su.MiddleName,
                       su.LastName,
                       l.Description,
                       t.Temperature,
                       t.UnitID,
                       t.Humidity');
    $this->db->from('temperaturelogs as t');
    $this->db->join('systemusers as su', 'su.UserID = t.Encoder');
    $this->db->join('locations as l', 't.LocationID = l.LocationID');
    $this->db->where("Cast(t.DateTime as date) >= '$start_date'");
    $this->db->where("Cast(t.DateTime as date) <= '$end_date'");
    $query = $this->db->get();
    if ($query->num_rows() > 0) 
    {
        return $query->result_array();
    }

当我尝试在 End Date 中输入此输入时.

我的输入: '; Truncate Table systemusers; #

给我这个错误:

您的 SQL 语法有误;请查看手册 对应于您的MariaDB服务器版本,以便使用正确的语法 靠近"截断表系统用户";#'' 在第 6 行

选择tDateTimesu .FirstNamesuMiddleNamesu .LastNamel .DescriptiontTemperaturet .UnitIDt .Humiditytemperaturelogs作为t加入systemusers作为 su su.UserID = t .Encoder加入locations l t .LocationID = l .LocationID 其中 Cast(t.DateTime as date)>= '2016-03-21' 和 Cast(t.DateTime as date) <= '';截断表 系统用户;#'

该错误与我的问题没有任何关系...

尝试,

$this->db->where('Cast(t.DateTime as date) >=', $start_date);
$this->db->where('Cast(t.DateTime as date) <=', $end_date);

在 where 子句中使用 $this->db->escape($start_date);

查看以下 SQL 查询转义 + 代码点火器

然后,您的活动查询将变为类似

$this->db->select('t.DateTime,
                       su.FirstName,
                       su.MiddleName,
                       su.LastName,
                       l.Description,
                       t.Temperature,
                       t.UnitID,
                       t.Humidity');
    $this->db->from('temperaturelogs as t');
    $this->db->join('systemusers as su', 'su.UserID = t.Encoder');
    $this->db->join('locations as l', 't.LocationID = l.LocationID');
    $this->db->where("Cast(t.DateTime as date) >= '".$this->db->escape($start_date)"'");
    $this->db->where("Cast(t.DateTime as date) <= '".$this->db->escape($end_date)"'");
    $query = $this->db->get();

CodeIgniter 提供了使用以下给定方法在 sql where 子句中设置自定义键/值方法。

您可以在第一个参数中包含运算符以控制比较:

$this->db->where('name !=', $name);
$this->db->where('id <', $id);
产生:其中名称 != 'Joe' 和 id <45