这是我的搜索引擎php代码。我在数据库中有三个字段:Title,Description和Url。但它只会显示与标题匹配的搜索查询。如何创建与标题,描述和网址匹配的搜索查询?
<?php
ini_set('display_errors',0); // turn off php notice & errors
$button = $_GET ['submit'];
$search = $_GET ['search'];
if(strlen($search)<=1)
echo "Search term too short";
else{
echo "You searched for <b>$search</b> <hr size='1'></br>";
mysql_connect("localhost","woogle","woogle");
mysql_select_db("search");
$search_exploded = explode (" ", $search);
foreach($search_exploded as $search_each)
{
$x++;
if($x==1)
$construct .="title LIKE '%$search_each%'";
else
$construct .="AND title LIKE '%$search_each%'";
}
$constructs ="SELECT * FROM searchengine WHERE $construct";
$run = mysql_query($constructs);
$foundnum = mysql_num_rows($run);
if ($foundnum==0)
echo "Sorry, there are no matching result for <b>$search</b>";
else
{
echo "$foundnum results found !<p>";
}
答案 0 :(得分:1)
试试这个:
foreach($search_exploded as $search_each)
{
$x++;
$search_each_e = mysql_real_escape_string($search_each); // To help prevent SQL injection
if($x==1)
$construct .="(title LIKE '%$search_each_e%' OR description LIKE '%$search_each_e%' OR url LIKE '%$search_each_e%')";
else
$construct .="AND (title LIKE '%$search_each_e%' OR description LIKE '%$search_each_e%' OR url LIKE '%$search_each_e%')";
}
You can escape the strings to prevent SQL injection。但是,我认为使用prepared statements是一种更强大的方法。
答案 1 :(得分:0)
试试这个:
$construct = " 1 "
foreach($search_exploded as $search_each)
{
$construct .=" AND (title LIKE '%$search_each%' OR description LIKE '%$search_each%' OR url LIKE '%$search_each%')";
}