Der er en række måder at gøre dette på, men den nemmeste måde ville være at gå gennem de acceptable kolonner og derefter tilføje passende.
// I generally use array and implode to do list concatenations. It avoids
// the need for a test condition and concatenation. It is debatable as to
// whether this is a faster design, but it is easier and chances are you
// won't really need to optimize that much over a database table (a table
// with over 10 columns generally needs to be re-thought)
$search = array();
// you want to white-list here. It is safer and it is more likely to prevent
// destructive user error.
$valid = array( 'condition', 'brand' /* and so on */ );
foreach( $valid as $column )
{
// does the key exist?
if( isset( $_GET[ $column ] ) )
{
// add it to the search array.
$search[] = $column . ' = ' . mysql_real_escape_string( $_GET[ $column ] );
}
}
$sql = 'SELECT * FROM TABLE_NAME WHERE ' . implode( ' AND ', $search );
// run your search.
Hvis du virkelig prøver at slippe af med 'hvis'-udsagn, kan du bruge dette:
$columns = array_intersect( $valid, array_keys( $_GET ) );
foreach( $columns as $column )
{
$search[] = $column . ' = ' . mysql_real_escape_string( $_GET[ $column ] );
}
$sql = 'SELECT * FROM TABLE_NAME WHERE ' . implode( ' AND ', $search );
Men du vil måske køre faktiske benchmarks for at afgøre, om det er en væsentligt bedre mulighed.