phpcodeigniteractiverecordparameter-passingquery-builder

Only add where conditions to CodeIgniter active record if user-provided values are not empty


Basically this code functions by pulling data entered by the user in the form and connects to the model which performs a query search based on the inputted information.

This code works but it only works when i enter both the $no and $first fields. But i need it to work so the user will be able to enter the $no and leave the other variable empty.

I thought i could use some sort of OR statement but i'm unsure how to implement it. Any help would be appreciated and i apologize if its not clear enough i'm fairly new when it comes to codeigniter.

Controller

public function query() 
{
    $no = $this->input->post('no');
    $first = $this->input->post('first');
    $this->load->model("test");
    $data['query'] = $this->test->query($no, $first);
    $this->load->view('query', $data);
}

Model

function query($no, $first)
{       
 return $query = $this->db->get_where('table', array('no' => $no,
 'first' => $first))->result();
}

View

<?php foreach($query as $row): ?>
<tr> 
    <td><?php echo $row->no; ?></td>
    <td><?php echo $row->date; ?></td>
    <td><?php echo $row->first; ?></td>
</tr>
<?php endforeach; ?>

Solution

  • How about just skipping any parameters that weren't provided?

    function query($no, $first)
    {
      $where = array();
    
      if ($no != '') $where['no'] = $no;
      if ($first != '') $where['first'] = $first;
    
      if (empty($where))
      {
        return array(); // ... or NULL
      }
      else
      {
        return $query = $this->db->get_where('table', $where);
      }
    }