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?
I suggest echoing out your query, it’ll help with debugging. Your query currently looks like:
As you can see, in the
INthe values are unquoted, so they’re interpreted as field names. You need to add quotes around each value in theIN.You can fix it by looping, and adding quotes around each value:
Or by imploding with
"','", and then adding quotes before and after:P.S. You should
mysql_real_escape_stringeach value in$_POST['Interest']to avoid SQL injections.