问问题
1076 次
2 回答
2
这里的问题(以及另一个答案)是该in
子句被引号包围,因此不会产生我们想要的结果。我们需要有效地将数组传递给查询。您的代码也容易受到 sql injection 的攻击。我强烈建议转向 PDO/prepared statements。我为这些国家增加了一点保护,但这绝不是万无一失的。
function prepareForSql($value, $key) {
return addslashes($value);
}
array_walk($_POST["chkUnr"], "prepareForSql");
$search_country = "'" . implode("','", $_POST["chkUnr"]) . "'";
$query = "";
$query .= "SELECT users.* FROM users";
if (isset($_POST['singles_online']) ? $_POST['singles_online'] : 0 == 1) {
$query .= " LEFT JOIN online ON online.user_id = users.id";
}
$query .= " WHERE";
if (isset($_POST['vip']) ? $_POST['vip'] : 0 == 1) {
$query .= " users.vip = 1 AND";
}
if (isset($_POST['profile_image']) ? $_POST['profile_image'] : 0 == 2) {
$query .= " users.profile_image = '2' AND";
}
if (isset($_POST['singles_online']) ? $_POST['singles_online'] : 0 == 1) {
$query .= " online.is_online = 1 AND";
}
$query .= " (id NOT IN (SELECT user_id FROM users_blocked WHERE blocked_id = '$user_id')) AND";
$query .= " (users.user_age >= '$age_from' AND users.user_age <= '$age_to') AND";
$query .= " (users.gender = '$gender_search') AND";
$query .= " users.country IN ($search_country)";
$search_query = mysql_query($query);
于 2012-12-11T14:28:20.560 回答
1
尝试
$search_country = implode(',',array_unique($_POST["chkUnr"]));
$query = "";
$query .= "SELECT users.* FROM users";
if (isset($_POST['singles_online']) ? $_POST['singles_online'] : 0 == 1) {
$query .= " LEFT JOIN online ON online.user_id = users.id";
}
$query .= " WHERE";
if (isset($_POST['vip']) ? $_POST['vip'] : 0 == 1) {
$query .= " users.vip = 1 AND";
}
if (isset($_POST['profile_image']) ? $_POST['profile_image'] : 0 == 2) {
$query .= " users.profile_image = '2' AND";
}
if (isset($_POST['singles_online']) ? $_POST['singles_online'] : 0 == 1) {
$query .= " online.is_online = 1 AND";
}
$query .= " (id NOT IN (SELECT user_id FROM users_blocked WHERE blocked_id = '$user_id')) AND";
$query .= " (users.user_age >= '$age_from' AND users.user_age <= '$age_to') AND";
$query .= " (users.gender = '$gender_search') AND";
$query .= " users.country IN ('$search_country')";
$search_query = mysql_query($query);
于 2012-12-11T13:35:52.310 回答