根据复选框过滤mysql结果

时间:2014-07-16 16:37:45

标签: mysql

我正在尝试根据已勾选的复选框过滤mysql结果。我的查询在第一次检查时工作但在第二个过滤器上没有返回任何内容我的复选框数组是$ _POST ['country'],我在GetSQLValueString函数中内爆以创建逗号分隔值 - (英国,法国)等。我使用MySQL IN子句进行多项选择。

我需要它来过滤多个国家/地区选择

if (isset($_POST['country_submit']) && $_POST['country'] != '') {   
    mysql_select_db($database_tub, $tub);
    $query_trade = sprintf("
SELECT u.user_id,
       u.contact_person,
       u.company,
       u.country,
       u.pic_small,
       u.website,
       SUM(u.trader_or_bond = %s
           AND t.user_id IS NOT NULL) AS count
FROM users u
LEFT JOIN trading t ON u.user_id = t.user_id
WHERE u.trader_or_bond = %s AND u.country IN(%s)
GROUP BY u.user_id
ORDER BY COUNT(t.user_id) DESC", 
GetSQLValueString('trader', "text"), 
GetSQLValueString('trader', "text"),
GetSQLValueString(implode(',', $_POST['country']), "text"));
    $trade = mysql_query($query_trade, $tub) or die(mysql_error());
} 

1 个答案:

答案 0 :(得分:0)

我已经提出了这个问题,但不确定MySQL注入是否安全,加上它不像我想的那么干净。

if (isset($_POST['country_submit']) && $_POST['country'] != '') {   

$SingleQuotes = "'".implode("', '", array_map('mysql_real_escape_string', $_POST['country']))."'";
    mysql_select_db($database_tub, $tub);
    $query_trade = sprintf("
SELECT u.user_id,
       u.contact_person,
       u.company,
       u.country,
       u.pic_small,
       u.website,
       SUM(u.trader_or_bond = %s
           AND t.user_id IS NOT NULL) AS count
FROM users u
LEFT JOIN trading t ON u.user_id = t.user_id
WHERE u.trader_or_bond = %s AND u.country IN($SingleQuotes)
GROUP BY u.user_id
ORDER BY COUNT(t.user_id) DESC", 
GetSQLValueString('trader', "text"), 
GetSQLValueString('trader', "text"));
$trade = mysql_query($query_trade, $tub) or die(mysql_error());
}