我创建了一个基本搜索表单,允许用户通过输入关键字来搜索我的数据库。如果他们的关键字匹配,则显示结果。但是,现在我想弄清楚当用户输入多个关键字时如何搜索数据库。例如,如果我想按名字搜索,我可以这样做,但如果我想用名字和姓氏搜索,我就不能这样做。我不确定如何将输入到表单中的字符串分解为两个单独的字符串,以便将其视为两个不同的字符串然后保存到一个变量中,该字符串将检查两个字符串数据库。
<?php
include("dbconnect.php");
if(!isset($_POST['search']))
{
header("Location:index.php");
}
$search_sql="SELECT * FROM speakers
WHERE fname LIKE '%".$_POST['search']."%'
OR lname LIKE '%".$_POST['search']."%'
OR city LIKE '%".$_POST['search']."%'
OR state LIKE '%".$_POST['search']."%'
OR ageGroup LIKE '%".$_POST['search']."%'
OR topic1 LIKE '%".$_POST['search']."%'
OR topic2 LIKE '%".$_POST['search']."%'
OR topic3 LIKE '%".$_POST['search']."%'";
$search_query=mysqli_query($dbc, $search_sql);
if(mysqli_num_rows($search_query) !=0)
{
$search_rs=$search_query->fetch_assoc();
}
?>
<p>Speaker Results</p>
<?php
if(mysqli_num_rows($search_query)!=0)
{
do { ?>
<p>
<?php
echo $search_rs['fname'];
echo $search_rs['lname'];
echo $search_rs['city'];
echo $search_rs['state'];
echo $search_rs['ageGroup'];
echo $search_rs['topic1'];
echo $search_rs['topic2'];
echo $search_rs['topic3'];
?>
</p>
<?php
} while ($search_rs=$search_query->fetch_assoc());
}
else
{
echo "No results found";
}
?>
答案 0 :(得分:0)
您可以使用正则表达式,例如:
SET @keywords = "john|doe";
SELECT * FROM speakers
WHERE fname REGEXP @keywords
OR lname REGEXP @keywords
OR city REGEXP @keywords;
我应该注意这种查询效率不高。我会考虑一些PHP搜索扩展:http://php.net/manual/en/refs.search.php