使用类似带通配符的查询的 codeigniter

Using codeigniter like query with wildcard

我正在尝试在 Codeigniter 上使用 like 查询。该函数将我的百分号 % 转义为 \%.

我的查询是:

SELECT *
        FROM (`invoices_rent`)
        WHERE `clerk_name` =  'BEAUTY'
        AND  `date`  LIKE '\%/\%/\%' 

$this->db->like('date', $date, 'none');

如何防止百分号被转义?

我正在尝试使用可以接收数字或通配符的日期进行筛选。所以我想要的是以一种我可以获得用户想要的月份、年份或日期的方式加入这些数据。所以我会将查询“%/02/2015”或“%/%/2015”传递给 return 我需要的数据范围。但是我对函数的转义有疑问。 我想我需要创建整个查询而不是使用这个 CodeIgniter 函数来创建它。遵循实际模型功能。

$date = "%/03/2015";

public function getallinvoices($type = false, $date = false, $clerk = false)
{
    if($type == "m")
        $table = "invoice_month";
    else
        $table = "invoices_rent";

    if($date != false)
        $this->db->like('date', $date, 'none');

    if($clerk != false && $clerk != "all")
        $this->db->where('clerk_name', $clerk);

    $query = $this->db->get($table);

    $this->output->enable_profiler(TRUE);
    print_r($query);

    return $query->result_array();
}

我希望查询 return 如:

SELECT *
FROM (`invoices_rent`)
WHERE `clerk_name` =  'BEAUTY'
AND  `date`  LIKE '%/03/2015'

我不确定你到底想在这里做什么。
将第三个参数添加为 none 不会在值周围添加通配符 (%) (或者它可能 escape 他们,在你的情况下)。

来自docs:

If you do not want to use the wildcard (%) you can pass to the optional third argument the option 'none'.

$this->db->like('title', 'match', 'none');
// Produces: WHERE title LIKE 'match'

因此,如果您想使用通配符,只需删除第三个参数即可。


(仅供参考)
假设 table,

`invoices_rent`

id    rent    invoice_number    clerk_name     date
1     150        INV001           BEAUTY     2015-03-04
2     250        INV002           BEAUTY01   2015-02-05
3     350        INV003           BEAUTY     2015-03-04

查询,

$date = '2015-03-04';
$this->db->like('date', $date);
$this->db->where('clerk_name');
$query = $this->db->get('invoices_rent');

return $query->result();

/**
* Result will give id: 1 & 3 as output
*/


编辑:

根据您更新的问题,基本上您需要 2015 年 3 月的所有行。当涉及日期范围时,您尝试的绝对不是正确的查询方式。您可以做的是获取月初(例如 2014-03-01)和月底(2014-03-31)并使用 between clause,这将为您提供所有行三月
以下是您的查询。

$month_start = date('Y-m-01', 'March');   # Month's start
$month_end = date('Y-m-t', 'March');      # Month's end

$this->db->where('date >=', $month_start);
$this->db->where('date <=', $month_end);
$this->db->where('clerk_name');
$query = $this->db->get('invoices_rent');

return $query->result();

/**
* Result will give id: 1 & 3 as output
*/