我正在尝试制作搜索功能,搜索多个列以查找基于关键字的匹配项。例如,当用户输入要搜索的关键字时,我需要跨五个类别列进行搜索,并在其任一类别列中返回包含该关键字的所有行的相应行名称。代码如下:
<?php
mysql_connect($dbhost, $dbuser, $dbpass) or die("could not connect.");
mysql_select_db($dbname) or die("could not find database.");
$result = "";
//collect info from database
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
//SQL query
$query = mysql_query("SELECT name FROM institutes WHERE category1 LIKE '%$searchq%' OR category2 LIKE '%$searchq%' OR category3 LIKE '%$searchq%' OR category4 LIKE '%$searchq%' OR category5 LIKE '%$searchq%'") or die("No records found.");
$count = mysql_num_rows($query);
if($count == 0)
{
$output = "There's no search result";
}
else {
while($array = mysql_fetch_assoc($query))
{
?>
<li><?php echo $array['name'];?></li>
<?php
}
?>
}
}
</ul>
我尝试了各种搜索方式,但每次都有错误或代码只返回每个行名称而不管条件如何。我们将不胜感激地解决这个问题。
答案 0 :(得分:0)
<?php
mysql_connect($dbhost, $dbuser, $dbpass) or die("could not connect.");
mysql_select_db($dbname) or die("could not find database.");
$result = "";
//collect info from database
if(isset($_POST['search'])&& $_POST['search'] != "")) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
//SQL query
$query = mysql_query("SELECT name FROM institutes WHERE category1 LIKE '%".$searchq."%' OR category2 LIKE '%".$searchq."%' OR category3 LIKE '%".$searchq."%' OR category4 LIKE '%".$searchq."%' OR category5 LIKE '%".$searchq."%'");
$count = mysql_num_rows($query);
if($count == 0)
{
$output = "There's no search result";
}
else {
while($row= mysql_fetch_assoc($query))
{
echo $row['name'];
}
}
}
?>