phpcodeignitercodeigniter-3codeigniter-query-builder

How can I do a between date query using codeigniter?


I´m trying to do a query where I select the start date and end date and page should display all the records stored between those dates, I have two inputs type date on view, well look at the examples.

This is my Controller:

public function reportes(){
      if ($_POST) {
          $fecha=$_POST['fecha'];
      }else{
        $fecha = '';
      }
      $fecha = $this->input->post('fecha');
     $fechaf = $this->input->post('fechaf');

      $this->db->select('empleados.Interno, empleados.Curp, empleados.Nombre, empleados.A_Paterno, empleados.A_Materno, cuentas.Clabe, cuentas.Banco, cuentas.Observaciones, cuentas.Status, cuentas.Fecha_alta');
    $this->db->from('empleados');
    $this->db->join('cuentas',"cuentas.Interno = empleados.Interno AND cuentas.Status !='I'", 'Left');
    $this->db->where('DATE(cuentas.Fecha_alta) BETWEEN cuentas.Fecha_baja AND cuentas.Fecha_alta', $fechaf, $fecha);
    $q = $this->db->get();
    $data['records'] = $q->result_array();
    $this ->load -> view('sitio/reportes', $data); 

    }

this is view:

<form action="<?php echo base_url();?>Inicio/reportes" method="post">
ENTRE <input type="date" name="fecha" id="fecha">
Y <input type="date" name="fechaf" id="fechaf">
<input type="submit" name="aceptar" id="aceptar" value="Aceptar" class="btn btn-primary">
</form>

I think i just need to pass the values of fecha (start_date) and fechaf (end_date) to the select query but I can´t seem to figure it out. Thanks in advance!


Solution

  • Do something like this :

    $fecha = $this->input->post('fecha');
    $fechaf = $this->input->post('fechaf');
    
    $this->db->select('empleados.Interno, empleados.Curp, empleados.Nombre, empleados.A_Paterno, empleados.A_Materno, cuentas.Clabe, cuentas.Banco, cuentas.Observaciones, cuentas.Status, cuentas.Fecha_alta');
    $this->db->from('empleados');
    $this->db->join('cuentas',"cuentas.Interno = empleados.Interno AND cuentas.Status !='I'", 'Left');
        //$this->db->where('DATE(cuentas.Fecha_alta) BETWEEN cuentas.Fecha_baja AND cuentas.Fecha_alta', $fechaf, $fecha);
    $this->db->where('cuentas.Fecha_alta >=', $fecha);
    $this->db->where('cuentas.Fecha_alta <=', $fechaf);