2012-04-16 49 views
-1

我一直在读通过,测试,以及从了解如何创建针对值的数组列匹配的MySQL的语句来了短...MySQL的WHERE阵列

这里就是我有...

<form id="form" action="index.php" method="post"> 
<? 
$query = "SELECT Interest FROM Interests"; 
$result = mysql_query($query); 
while ($row = mysql_fetch_assoc($result)) 
{ 
    echo '<input type="checkbox" name="Interest[]" value="' . $row['Interest'] . '" /> ' . $row['Interest'] . '<br />'; 
} 
?> 
<input id="Search" name="Search" type="submit" value="Search" /> 
</form> 

<? 
if (isset($_POST['Search'])) 
{ 
    $InterestMatches = implode(',', $_POST['Interest']); 
    $query = "SELECT MemberID FROM MemberInterests WHERE Interest IN ($InterestMatches)"; 
    $result = mysql_query($query) or die(mysql_error()); 
    if (!$result) { 
     $message = 'Invalid query: ' . mysql_error() . "\n"; 
     $message .= 'Whole query: ' . $query; 
     die($message); 
    } 
    while ($row = mysql_fetch_assoc($result)) 
    { 
     $ResultingMemberIDs[] += $row['MemberID']; 
    } 
} 
?> 

而我总是得到的是同样的错误......

Unknown column 'WhateverInterest' in 'where clause' 

有人可以告诉我什么,我做错了,我需要做的纠正呢?

+0

您能得到什么,如果你打印'$ query'?另外一定要清除你输入到查询中的任何变量,恶意用户可以注入sql。 – Jim 2012-04-16 16:41:06

+0

谢谢你,但这只是测试代码,我生病的人死于那些想要告诉他们所有关于sql注入攻击的帖子,并且在我的帖子中给我一个负数... – 2012-04-16 17:29:48

+0

我不是downvoter ,也不会拖延寻找sql注入漏洞的问题。我只是添加了这个,因为我已经提出了一个问题。 – Jim 2012-04-17 11:56:18

回答

3

我建议回应你的查询,它会帮助调试。您的查询目前看起来像:

SELECT MemberID FROM MemberInterests WHERE Interest IN (WhateverInterest,Testing) 

正如你所看到的,在IN的值是不带引号的,所以他们解释为字段名。您需要在IN中的每个值周围添加引号。

您可以通过循环和周围的每个值加上引号修复:

foreach($_POST['Interest'] as &$intrest){ 
    $intrest = "'$intrest'"; 
} 
$InterestMatches = implode(',', $_POST['Interest']); 

或用"','"爆,然后前后分别增加报价:

$InterestMatches = "'" . implode("','", $_POST['Interest']) . "'"; 

附:您应该在$_POST['Interest']的每个值中使用mysql_real_escape_string以避免SQL注入。

+0

我用你的代码,谢谢,它使它工作...现在唯一的问题是,查询结果给我所有的结果有任何兴趣...例如,如果我搜索2个不同的兴趣,它会给我所有的结果,不管他们是否拥有所有的利益......你知道我的意思吗? – 2012-04-16 17:01:19

+1

@MichaelConklin:这就是'IN'的工作原理。 'IN'与具有多个'OR'语句相同。 – 2012-04-16 17:18:14

+0

所以没有办法绕过它? – 2012-04-16 17:20:01

2

尝试

$InterestMatches = '"' . implode('","', $_POST['Interest']) . '"'; 
+0

对不起,大声笑,你的帖子太小了,我什至没有看到它,但它看起来像就像我从其他工作响应者那里使用的那个一样...... – 2012-04-16 17:05:22