繁体   English   中英

如何在 codeigniter 中使用可选参数

[英]how to use optional parameter in codeigniter

我正在尝试在 CodeIgniter 中使用可选参数。 我的 controller function 如下所示。

public function expenses($head = null, $date_to= null, $date_from =null)
    {
        $query_expenses =  $this->user_model->get_all_expenses($head,$date_to,$date_from);

        //more code
    }

我的 Model 代码如下

public function get_all_expenses($head = null, $date_to= null, $date_from =null)
    {
        $array = array('cat_id ==' => $head, 'date >' => $date_from, 'date <' => $date_to);
        $this->db->select("*,category.name as cat_name,expense.created_at as created_at_expense");
        $this->db->from('expense')->where($array);

        //more code
    }

我收到如下错误。

A Database Error Occurred

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '`NULL` AND `date` > AND `date` <' at line 5

SELECT *, `category`.`name` as `cat_name`, `expense`.`created_at` as `created_at_expense` FROM `expense` JOIN `category` ON `expense`.`cat_id` = `category`.`id` JOIN `users` ON `expense`.`user_id` = `users`.`id` WHERE `cat_id` = `IS` `NULL` AND `date` > AND `date` <

Filename: models/User_model.php

Line Number: 603

在此处输入图像描述

尝试这个:

public function get_all_expenses($head = null, $date_to= null, $date_from =null)
{
    $filter = [];
    if( $head ) $filter[] = ['cat_id' => $head]; // == is default
    if( $date_to ) $filter[] = ["date <" => $date_to];
    if( $date_from ) $filter[] = ["date >" => $date_from];

    $this->db->select("*,category.name as cat_name,expense.created_at as created_at_expense");
    $this->db->from('expense')->where($filter);

    //more code
}

您不能将数组用于“IS NULL”,您必须将其作为整个字符串提供。

public function get_all_expenses($head = null, $date_to = null, $date_from = null)
{
    $this->db->select("*, category.name as cat_name, expense.created_at as created_at_expense");
    $this->db->from('expense');

    if (!empty($head)) {
        $this->db->where('cat_id', $head);
    } else {
        $this->db->where('cat_id IS NULL');
    }

    if (!empty($date_to) && !empty($date_from)) {
        $this->db->where('date >', $date_from);
        $this->db->where('date <', $date_to);
    }
    
    //more code
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM