【发布时间】:2017-10-01 21:30:38
【问题描述】:
我正在创建一个用户搜索,用户可以在其中根据用户名、语言和/或位置搜索其他用户。至少需要一个字段,例如,您可以只搜索用户名,或用户名和位置等。
考虑到某些参数可能为空,我在编写 MYSQL 查询时遇到了困难。我目前尝试最多使用两个参数:
PHP/MySQL (PDO)
$data = json_decode(file_get_contents("php://input"));
$user = $data->user; //'null' if left blank
$location = $data->location; //'null' if left blank
$sql = "SELECT user, spokenLanguages, profileImage
FROM users WHERE user LIKE :user
AND (town = LOWER(:location) OR country = LOWER(:location))";
如果定义了 $user 和 $location,这将非常有效,但如果定义了 $user 并且 $location 不等于 null,我只需要包含位置 WHERE 子句。类似地,如果定义了 $location 而 $user 是null,则不应考虑 user 子句。有什么我不知道的快速方法吗?还是会用 if/else 语句扩展查询?
任何帮助将不胜感激。
【问题讨论】: