Combination of field search using PHP & MYSQL

后端 未结 3 856
长情又很酷
长情又很酷 2020-12-22 06:39

I am working on an assignment using PHP & MYSQL.

one of the tasks is to search on any combination of the fields. That includes Dropdown boxes populated from the

3条回答
  •  暖寄归人
    2020-12-22 06:50

    I've done something similar in the past where I checked the value from different fields and then added them to a series of arrays. I created an array for select, from, where, order. You can do similar for other sets like group or limit. Then I ran 'array_unique', imploded them and put them into the SQL string.

    $array_select = array('users.Id'); // SET SOME DEFAULTS SO THE QUERY WILL ALWAYS RUN
    $array_from = array('users');
    $array_where = array();
    $array_order = array();
    
    if (isset($first_name)) {
        $array_select[] = 'First_Name';
        $array_from[] = 'users';
    }
    
    if (isset($city)) {
        $array_select[] = 'City';
        $array_from[] = 'user_contact';
        $array_where[] = 'users.Id = user_contact.City';
    }
    
    if ($array_select) {
        $array_select = array_unique($array_select);
        $string_select = implode(', ', $array_select);
    }
    if ($array_where) {
        $array_where = array_unique($array_where);
        $string_where = 'WHERE '.implode(' AND ', $array_where);
    }
    // REPEAT FOR OTHERS ...
    
    
    
    // BUILD THE QUERY OUT
    $sql = 'SELECT '.$string_select.' FROM '.$string_from.' '.$string_where.' ...
    

提交回复
热议问题