I am working on a PHP MVC project for my portfolio. Its an web app where you can store contacts (email and phone number). I am having trouble with filtering contacts based on filter form that has 3 options https://ibb.co/8dJbSWd
I wrote code that works fine but I am sure there is better way of doing this. Here is the code that I wrote for solving this problem.
public function filterContacts($user_id, $group, $email, $phone){
$query = 'SELECT * FROM contacts WHERE user_id = :user_id ';
//Nothing is selected
if($group == '0' && $email == '' && $phone == ''){
$this->db->query($query . ' ORDER BY name');
$this->db->bind(':user_id', $user_id);
return $this->db->resultSet();
//Everything is selected
} else if ($group !== '0' && $email !== '' && $phone !== ''){
$query .= 'AND contact_group = :group AND email != "" AND phone_number != ""';
$this->db->query($query . 'ORDER BY name');
$this->db->bind(':user_id', $user_id);
$this->db->bind(':group', $group);
return $this->db->resultSet();
//Just group
} else if ($group !== '0' && $email == '' && $phone == ''){
$query .= 'AND contact_group = :group ';
$this->db->query($query . 'ORDER BY name');
$this->db->bind(':user_id', $user_id);
$this->db->bind(':group', $group);
return $this->db->resultSet();
//Just email
} else if ($group == '0' && $email !== '' && $phone == ''){
$query .= 'AND email != "" ';
$this->db->query($query . 'ORDER BY name');
$this->db->bind(':user_id', $user_id);
return $this->db->resultSet();
//Just phone
} else if ($group == '0' && $email == '' && $phone !== ''){
$query .= 'AND phone_number != "" ';
$this->db->query($query . 'ORDER BY name');
$this->db->bind(':user_id', $user_id);
return $this->db->resultSet();
//Group and email
} else if($group !== '0' && $email !== '' && $phone == ''){
$query .= 'AND contact_group = :group AND email != ""';
$this->db->query($query . 'ORDER BY name');
$this->db->bind(':user_id', $user_id);
$this->db->bind(':group', $group);
return $this->db->resultSet();
//Group and phone number
} else if($group !== '0' && $email == '' && $phone !== ''){
$query .= 'AND contact_group = :group AND phone_number != ""';
$this->db->query($query . 'ORDER BY name');
$this->db->bind(':user_id', $user_id);
$this->db->bind(':group', $group);
return $this->db->resultSet();
//Email and phone number
} else if($group == '0' && $email !== '' && $phone !== ''){
$query .= 'AND phone_number != "" AND email != ""';
$this->db->query($query . 'ORDER BY name');
$this->db->bind(':user_id', $user_id);
return $this->db->resultSet();
}
}
As you can see I used a lot of if statements to make different queries in Contact model which is possible because i have only 3 filtering options but I cannot imagine doing this with 10 options.
So I was wondering is there a better way of solving this?
Here is link to my github repository if you want to see rest of the code https://github.com/Smiley-dev/Phonebook-demo