如何用Codeigniter的方式编写数据库查询来搜索日期字段中的月份?

时间:2012-01-02 16:08:18

标签: codeigniter codeigniter-2

你能告诉我如何用Codeigniter的方式编写数据库查询来搜索日期字段中的月份吗?或者,您能否告诉我如何以codeigniter的方式编写以下查询?

提前致谢:)

 "SELECT attendanceno FROM attendance WHERE (barcodeid = '$studentid') AND  (month(attendancedate)='$month' AND year(attendancedate)='$year') ";

编辑

感谢Stefan,他在下面回答了我的问题。阅读他的帖子后,我也尝试了以下脚本,发现它有效。这就是为什么我只是想分享以防任何人想要使用它。但所有的功劳都归功于斯特凡。 :)

  $this->db->select('*');
  $this->db->from('attendance');
  $this->db->where('barcodeid', $studentid);
  $this->db->where('month(attendancedate)', $month);
  $this->db->where('year(attendancedate) ', $year);
  $this->db->order_by('attendancedate ','ASC');     
  $getData = $this->db->get('', $perPage, $uri);                        

2 个答案:

答案 0 :(得分:2)

如果日期和月份是字符串:

$this->db->query("SELECT attendanceno FROM attendance WHERE (barcodeid = ?) AND  (month(attendancedate)=? AND year(attendancedate)=?)", array($studentid, $month,$year));

如果它们是整数

$this->db->query("SELECT attendanceno FROM attendance WHERE (barcodeid = ?) AND  (MONTH(attendancedate)='?' AND YEAR(attendancedate)='?')", array($studentid, $month,$year));

答案 1 :(得分:0)

假设:

  • CodeIgniter 2.2.0
  • Oracle 11数据库

    //Option 1, raw SQL
     $sql = "
      SELECT DISTINCT <DATE_COLUMN>
      FROM <TABLE NAME>
      WHERE 1=1
        AND EXTRACT(month FROM <DATE_COLUMN>) = $month
        AND EXTRACT(year FROM <DATE_COLUMN>) = $year
     ";
     $query = $this->db->query($sql);
    
    //Option 2, CI db functions
    $this->db->distinct();
    $this->db->select('<DATE_COLUMN>');
    $this->db->where('EXTRACT(month FROM <DATE_COLUMN>) =', $month);
    $this->db->where('EXTRACT(year FROM <DATE_COLUMN>) =', $year);
    $query = $this->db->get('<TABLE NAME>');
    

两者都会产生以下内容:$ month = 3和$ year = 2017:

     CI_DB_oci8_result Object
     (
         [stmt_id] => Resource id #9
         [curs_id] => 
         [limit_used] => 
         [conn_id] => Resource id #1
         [result_id] => 1
         [result_array] => Array
             (
                 [0] => Array
                     (
                         [<DATE_COLUMN>] => 22-MAR-17
                     )

                 [1] => Array
                     (
                         [<DATE_COLUMN>] => 14-MAR-17
                     )

                 [2] => Array
                     (
                         [<DATE_COLUMN>] => 02-MAR-17
                     )

                 [3] => Array
                     (
                         [<DATE_COLUMN>] => 06-MAR-17
                     )

             )

         [result_object] => Array
             (
             )

         [custom_result_object] => Array
             (
             )

         [current_row] => 0
         [num_rows] => 4
         [row_data] => 
     )