Search code examples
phpmysqlwildcardsql-like

Simplifying mysql filter query


I'm building a platform for a casting manager to catalog Actors and be able to browse them. My table 'actor' is set up with first name, last name, email, phone, address etc.

I have a browse.php page which has a form to filter results. Here's my class that I need help simplifying as well as getting rid of the wild card result when a field is null.

I pass through the form data into an array, $search, and the class checks if the array section is filled and writes to the SQL query.

public function getActors($search) {
    if(isset($search)) {
        if($search["first_name"] == NULL) { $first_name = "LIKE '%'"; } else { $first_name = "LIKE '".$search["first_name"]."'"; }
        if($search["last_name"] == NULL) { $last_name = "LIKE '%'"; } else { $last_name = "LIKE '".$search["last_name"]."'"; }
        if($search["gender"] == NULL) { $gender = "LIKE '%'"; } else { $gender = " = '".$search["gender"]."'"; }
        if($search["address_state"] == NULL) { $address_state = "LIKE '%'"; } else { $address_state = " = '".$search["address_state"]."'"; }
        if($search["ethnicity"] == NULL) { $ethnicity = "LIKE '%'"; } else { $ethnicity = " = '".$search["ethnicity"]."'"; }
        if($search["status"] == NULL) { $status = "LIKE '%'"; } else { $status = " = '".$search["status"]."'"; }

        $sql = "SELECT * FROM actor WHERE
            first_name ".$first_name." AND
            last_name ".$last_name." AND
            gender ".$gender." AND
            address_state ".$address_state." AND
            ethnicity ".$ethnicity." AND
            status ".$status."
        ";          
    } else {
        $sql = "SELECT * FROM actor";   
    }
    $s = mysql_query($sql) or die (mysql_error());
    $numrows = mysql_num_rows($s);

    for($x=0; $x < $numrows; $x++){
        $actorArray[$x] = mysql_fetch_row($s);
    }
    return $actorArray;
}   

Any help on simplifying this or suggestions?


Solution

  • What about (within the isset block)...

    $fields = array('first_name','last_name','gender','address_state','ethnicity','status');
    $parts = array();
    foreach($fields as $field) {
      if(!empty($search[$field])) {
        $parts[] = $field . ' LIKE "' . $search[$field] . '"';
      }
    }
    $sql = "SELECT * FROM actor WHERE " . implode(' AND ', $parts);
    

    And as mentioned by @Dvir, it's better to use positional parameters in your SQL statements.