【问题标题】:how to use optional parameter in codeigniter如何在codeigniter中使用可选参数
【发布时间】:2022-01-14 10:27:48
【问题描述】:

我正在尝试在 CodeIgniter 中使用可选参数。我的控制器功能如下。

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
    }

我的模型代码如下所示

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

【问题讨论】:

    标签: php function codeigniter model controller


    【解决方案1】:

    试试这个:

    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
    }
    

    【讨论】:

      【解决方案2】:

      你不能使用一个数组来表示“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
      }
      

      【讨论】:

        猜你喜欢
        • 2012-12-20
        • 1970-01-01
        • 1970-01-01
        • 2018-03-25
        • 2011-02-02
        • 1970-01-01
        • 2014-09-16
        • 2020-10-03
        • 2020-01-30
        相关资源
        最近更新 更多