简体   繁体   中英

Running PHP search script with empty parameters returns entire MySQL table

When I run the following MySQL query via PHP and all of the elements of $_GET() are empty strings, all the records in the volunteers table are returned (for obvious reasons).

$first = $_GET['FirstName'];
$last = $_GET['LastName'];
$middle = $_GET['MI'];

$query = "SELECT * FROM volunteers WHERE 0=0";

if ($first){
    $query .= " AND first like '$first%'";
}

if ($middle){
    $query .= " AND mi like '$middle%'";
}

if ($last){
    $query .= " AND last like '$last%'";
}

$result = mysql_query($query);

What is the most elegant way of allowing empty parameters to be sent to this script with the result being that an empty $result is returned?

my solution:

$input = Array(
    'FirstName' => 'first',
    'LastName'  => 'last',
    'MI'        => 'mi'
);

$where = Array();
foreach($input as $key => $column) {
    $value = trim(mysql_escape_string($_GET[$key]));
    if($value) $where[] = "`$column` like '$value%'";
}
if(count($where)) {
    $query = "SELECT * FROM volunteers WHERE ".join(" AND ", $where);
    $result = mysql_query($query);
}

There's no point in running a (potentially) expensive query if there's nothing for that query to do. So instead of trying to come up with an alternate query to prevent no-terms being searched, just don't run the search at all if there's no terms:

$where = '';
... add clauses ...
if ($where !== '') {
   $sql = "SELECT ... WHERE $where";
   ... do query ...
} else {
   die("You didn't enter any search terms");
}

With your current code, if everything is empty, you will get the WHERE 0=0 SQL which is TRUE for all rows in the table.

All you have to do is remove the if statements...

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