Skip to content
Advertisement

Codeigniter MySQL filtering data as per user ID in the session

I have following function in my model to select records as per the user ID in the session.

public function getOfficer()
    {
     $usr = $this->session->userdata('id_user');
     $userArray = $this->db->order_by('last_name','ASC')->where_in('tbl_officer.p_code', [8,10,24]);
     $userArray1 = $this->db->order_by('last_name','ASC')->get_where('tbl_officer', array('status' => 1, 'usr'=>$this->session->userdata('id_user')));

     if($usr == 4){
        $this->db->where('p_code',$userArray );
     }else{
        $this->db->where('usr',$userArray1);
     }
     $q = $this->db->get('tbl_officer');
     if ($q->num_rows() > 0) {
        return $q->result();
     }
     return false;
    }

If the user 4 in the session, records should be filtered by p_code [8,10,24] and any other user in the session, records should be filtered as per usr. usr column includes user ids like 1,2,3,4 etc.

But the function outs following error and didn’t get the expected result.

Error Number: 42000/1064

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ‘WHERE p_code =’ at line 2

SELECT * WHERE p_code =

Filename: C:/xampp/htdocs/doahrm/application/models/Officer_model.php

Line Number: 106

Line Number 106 is $q = $this->db->get(); in the function.

What may be going wrong ? Can anyone help ?

Advertisement

Answer

According to the raw sql, the from table_name is lost:

SELECT * WHERE `p_code` = ...

So you are lossing your table:

$q = $this->db->get('table_name');

And I think your code need to look like this:

public function getOfficer()
{
     $usr = $this->session->userdata('id_user');
     if ($usr == 4) {
         $query = $this->db->order_by('last_name','ASC')->where_in('tbl_officer.p_code', [8,10,24]);
     } else {
         $query = $this->db->order_by('last_name','ASC')
                           ->where(array('status' => 1, 'usr'=>$usr));
     }
     $query = $query->get('tbl_officer');
     if ($query->num_rows() > 0) {
         return $query->result();
     } else {
         return false;
     }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement