使用 PHP 搜索 mySQL,使用 WHERE 通配符或 IF 语句?
我让用户按城市搜索我的数据库中的数据。 我的查询如下所示:
$results = mysql_query("SELECT * FROM mydb WHERE City='".$city."' LIMIT 10");
我希望用户能够搜索“所有城市” ',所以我想删除 WHERE 语句 if $city=='all city';或者使用 WHERE 语句的通配符来匹配数据库中的所有城市。
我曾经有一个 IF 语句在两个查询之间切换,但我想添加更多过滤器,如国家/所有国家、邮政编码/所有邮政编码等,所以我宁愿保留一个动态 SQL 查询。
I'm letting users search my database for data by city.
My query looks like:
$results = mysql_query("SELECT * FROM mydb WHERE City='".$city."' LIMIT 10");
I want a user to be able to search 'all cities', so I'd like to either remove the WHERE statement if $city=='all cities'; or use a wildcard for the WHERE statement that matches all cities in the db.
I used to have an IF statement that switched between two queries, but I want to add more filters like country/all countries, zipcode/all zipcodes, etc, So I'd rather keep one dynamic SQL query.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,您仍然可以只有一个查询并动态构建 where 子句,如下所示:
Well, you could still have just one query and build the where clause dynamically, as such:
一种方法是使用 case 语句:
如果用户正在搜索“所有城市”,这会将 WHERE 语句变为:
始终为真(至少对于非空城市;))
PS 确保您正在运行这些查询使用只读 MySQL 帐户。用户可以在
$city
参数中输入有趣的内容!One way would be a case statement:
If the user is searching for 'All cities', this turns the WHERE statement into:
Which is always true (at least for non-null cities ;))
P.S. Make sure you're running these queries using a read-only MySQL account. The user could enter funny stuff into the
$city
parameter!您可以尝试允许他们输入通配符。
如果您认为用户能够胜任,
You could try
and permit the users to enter wildcards, if you think they'd be up to it.
虽然不是 PHP 程序员,但此伪代码可能提供一个选项...有条件地构建您的 where 子句。此外,我会使用参数化查询而不是直接构建字符串来防止 SQL 注入攻击。
现在,始终添加您的国家/地区选择
运行查询
although not PHP programmer, this pseudocode might offer an option... conditionally build out your where clause. Additionally, I would do it with parameterized queries instead of direct string building to prevent sql-injection attacks.
Now, always add your country selection
Run the query