使用空参数运行 PHP 搜索脚本会返回整个 MySQL 表
当我通过 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);
允许将空参数发送到此脚本并导致返回空的 $result
的最优雅的方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我的解决方案:
my solution:
如果查询没有什么可做的,那么运行(可能)昂贵的查询是没有意义的。因此,与其尝试提出替代查询来防止搜索无术语,不如在没有术语的情况下根本不运行搜索:
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 0=0 SQL,这对于表中的所有行都是 TRUE。
您所要做的就是删除 if 语句......
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...