具有AND条件的PHP SQL IN运算符

时间:2015-12-21 15:33:31

标签: php mysql sql

我有一个PHP SQL查询,如下所示:

$search = mysql_query("SELECT * FROM `data` WHERE (`state` IN ($userStr)) AND ('Scholarship Type' LIKE '%$stype%')")

$ userstr是最终用户在复选框中选择的状态数组。这部分工作正常,但是当我介绍奖学金类型的下一个条件时,它将无法正常工作。

以下是完整代码:

<html>
<head>
<link rel="stylesheet" type="text/css" href="results.css">
</head>
</html>
<?php

$state = $_POST['state'];
$stype = $_POST['stype'];


$connection = mysql_connect('198.71.225.63:3306', 'newmslsuper', 'blank'); //The Blank string is the password
mysql_select_db('msl_data');

if(isset($_POST['col'])){
    $state1 = $_POST['col'];
}

$userStr = implode(',', $state1);



$search = mysql_query("SELECT * FROM `data` WHERE (`state` IN   ($userStr)) AND ('Scholarship Type' LIKE '%$stype%')");
$count=mysql_num_rows($search);
if ($count==0) { 
echo 'Sorry your search returned no results. Please try again.'; 
}
else {

$fields_num1 = mysql_num_fields($search);


echo "<table><tr>";

// printing table headers
for($i=0; $i<$fields_num1; $i++)
{
$field1 = mysql_fetch_field($search);
echo "<th>{$field1->name}</th>";
}
echo "</tr>\n";

// printing table rows
while($row1 = mysql_fetch_row($search))
{
echo "<tr>";

// $row is array... foreach( .. ) puts every element
// of $row1 to $cell1 variable
foreach($row1 as $cell1)
    echo "<td>$cell1</td>";

echo "</tr>\n";
}
}
mysql_close(); //Make sure to close out the database connection


?>

1 个答案:

答案 0 :(得分:1)

删除single quotes并在列名中使用backticks escape space

SELECT * FROM `data` 
WHERE `state` IN ($userStr) 
AND `Scholarship Type` LIKE '%$stype%'
  --^-- Here       --^--here