php - SELECT Query, WHERE selects all when "" is empty -
the aim
hi, i'm trying shorten code building query dynamically based on $_get
. current have every possible if statement relevant select
query. create dynamic system feature updates.
current progress
//set filter based on url if ($_get[game] != "") { $gamefilter = $_get[game]; } else { $gamefilter = ''; } if ($_get[region] != "") { $regionfilter = $_get[region]; } else { $regionfilter = ''; } if ($_get[console] != "") { $consolefilter = $_get[console]; } else { $consolefilter = ''; } $result = get_matchfinder($gamefilter, $regionfilter, $consolefilter);
//the function
function get_matchfinder($gamefilter, $regionfilter, $consolefilter) { //set varibles $database = 'matchfinder'; $order = 'desc'; $limit = '20'; //query function $connection = connection(); $sql = 'select * '. $database .' game = "'.$gamefilter.'" , region = "'.$regionfilter.'" , console = "'.$consolefilter.'" order id '. $order .' limit '. $limit .''; $response = mysqli_query($connection, $sql); //return return $response; }
problem currenly works when of filters active if 1 of them isn't whole query fails, know thats because try select matching ''
.
so questions how make search when filters not set?
you should build query parts depending on length of filter:
$sql = ' select * '.$database.' '; $filters = array(); if (strlen($gamefilter) > 0) { $filters[] = 'game = "'.mysqli_escape_string($connection, $gamefilter).'"'; } if (strlen($regionfilter) > 0) { $filters[] = 'region = "'.mysqli_escape_string($connection, $regionfilter).'"'; } if (strlen($consolefilter ) > 0) { $filters[] = 'console= "'.mysqli_escape_string($connection, $consolefilter).'"'; } if (count($filters) > 0) { $sql .= ' '.implode(' , ', $filters); } if (strlen($oder) > 0) { $sql .= ' order id '.$order; } if ($limit > 0) { $sql .= ' limit '.$limit; } $response = mysqli_query($connection, $sql);
what you're doing there building array of conditions, based on length of condition. if condition's input empty string, isn't added array. @ end, if there filters, use implode
bind conditions string. way implode
works, if there's 1 condition, glue string isn't used.
it bears mentioning exposing sql injection. above code shows use of mysqli_escape_string
escape input, should in parameterized queries take full precaution: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php -- above sample different if used paraterized queries, more safe.
documentation
strlen
- http://php.net/manual/en/function.strlen.phpimplode
- http://php.net/manual/en/function.implode.php- mysql parameterized queries - http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
Comments
Post a Comment