Filtering data from MYSQL database based on parameters passed with POST request
The entire long conditional is definitely worth to be decomposed and consolidated.

The main mechanics of optimization is based on 3 aspects:


determining a common logic/behavior that needs to be unified. In your case such a common fragment is:

$this-&gt;db-&gt;query($query . 'ORDER BY name');
$this-&gt;db-&gt;bind(':user_id', $user_id);
return $this-&gt;db-&gt;resultSet();

considering only populated fields
collecting bindings for particular fields




The final optimized function becomes as below:

public function filterContacts($user_id, $group, $email, $phone){

    $query = 'SELECT * FROM contacts WHERE user_id = :user_id';
    $bindings = [':user_id':=&gt; $user_id];

    if ($group !== '0') {
        $query .= ' AND contact_group = :group';
        $bindings[':group'] = $group;
    }    
    if ($email !== '') {
        $query .= ' AND email != ""';
    }
    if ($phone !== '') {
        $query .= ' AND phone_number != ""';
    }

    $this-&gt;db-&gt;query($query . ' ORDER BY name');
    foreach ($bindings as $k =&gt; $v) {
        $this-&gt;db-&gt;bind($k, $v);
    }

    return $this-&gt;db-&gt;resultSet();
}




In case if your DB clent $this-&gt;db allows to pass an array of bindings you can just  replace the loop with $this-&gt;db-&gt;bind($bindings); (check your DB client interface)