简体   繁体   English

使用空参数运行PHP搜索脚本将返回整个MySQL表

[英]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). 当我通过PHP运行以下MySQL查询并且$_GET()所有元素均为空字符串时,将返回volunteers表中的所有记录(出于明显的原因)。

$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? 允许将空参数发送到此脚本并$result返回空$result的最优雅方法是什么?

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. 使用当前代码,如果所有内容均为空,则将获得WHERE 0 = 0 SQL,对于表中的所有行均为TRUE。

All you have to do is remove the if statements... 您所要做的就是删除if语句...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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