-1

I have been reading through, testing, and coming up short from understanding how to create a MySQL statement that matches a column against an array of values...

Here's what I have...

<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'];
    }
}
?>

And what I always get is the same error...

Unknown column 'WhateverInterest' in 'where clause'

Can someone please tell me what I am doing wrong, what I need to do to correct this?

4

2 に答える 2

3

I suggest echoing out your query, it'll help with debugging. Your query currently looks like:

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

As you can see, in the IN the values are unquoted, so they're interpreted as field names. You need to add quotes around each value in the IN.

You can fix it by looping, and adding quotes around each value:

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

Or by imploding with "','", and then adding quotes before and after:

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

P.S. You should mysql_real_escape_string each value in $_POST['Interest'] to avoid SQL injections.

于 2012-04-16T16:41:16.207 に答える
2

Try

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