问题
I'm trying to make a search feature that will search multiple columns to find a keyword based match. For example when the user enters a keyword to search, i need to conduct a search across five category columns and return the corresponding row names of all the rows that contain the keyword in either of its category columns. The code is as follows:
<?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>
I have tried various ways to search but every time, either there is an error or the code just returns every row name irrespective of conditions. a solutions to the problem will be appreciated.
回答1:
<?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'];
}
}
}
?>
来源:https://stackoverflow.com/questions/36371155/searching-across-multiple-columns