-1

我一直在阅读、测试和理解如何创建一个 MySQL 语句来匹配一列与一组值......

这就是我所拥有的...

<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'

有人可以告诉我我做错了什么,我需要做些什么来纠正这个问题?

4

2 回答 2

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']) . "'";

PS您应该mysql_real_escape_string输入每个值$_POST['Interest']以避免SQL注入。

于 2012-04-16T16:41:16.207 回答
2

尝试

$InterestMatches = '"' . implode('","', $_POST['Interest']) . '"';
于 2012-04-16T16:42:18.173 回答