简体   繁体   中英

Filtering MYSQL data using dropdown boxes

I have populated an html page with a table from the database. I want to add dropdown boxes at the top that can filter out unnecessary data. How would I go about sending this information to the database to make a query so that I can filter out data with multiple variables?

For example, I have 5 categories, A, B, C, D, and E. I have used PHP code to populate the boxes with the possible values/entries for A, B, C, D, and E. I've also added a "NULL entry" in case the user does not want to include this column as part of the filter.

So right now as it stands, for the respective columns we can have:

Apple, always, as, amazing, as, almonds, NULL.
Belly, boosts, bad, NULL.
Candy, can, create, NULL.
Dandy, does, do, don't, NULL.
Elements, exist, NULL.

How would I go about sending the information to the database when the variables are indefinite? They may or may not be set.

I figured I'd start by seeing if the variables were set in the first place by using the isset(), but how would I proceed from there? It seems like a lot of 'if' statements. All I need to do is to change the query based on the values of the variables the user enters. But I don't see an easy way of doing that.

I'll simply be adding "WHERE A = this AND B = that AND C = thisthat AND .." to the end of the query but what if one or more or all of those entries are null?

Thanks a lot for any help.

You can easily construct your WHERE query as follows

$where = array();

if ($A != '')
{ 
    $where[] = 'A = "' . $A . '"';
}

if ($B != '')
{ 
    $where[] = 'B = "' . $B . '"';
}

if ($C != '')
{ 
    $where[] = 'C = "' . $C . '"';
}

if ($D != '')
{ 
    $where[] = 'D = "' . $D . '"';
}

if ($E != '')
{ 
    $where[] = 'E = "' . $E . '"';
}

// Now get the $where
$final_where = '';
if (count($where) > 0)
{
    $final_where = implode(' AND ', $where);
}

// $final_where will contain
// A = 'ab' AND B = 'cd' etc.

NOTE Please make sure to sanitize your input. So for instance you need to add a check for $A that it contains the values that you expect it to contain. Anything else must be discarded. You can use the in_array for instance like so:

$a_array = array('first value', 'second value', 'third value');
if (in_array($A, $a_array))
{
    // Valid choice - we can use it
}
else 
{
    // Not valid set $A to null
    $A = '';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM