我有一个数据库,我有标题
Titles
Celeste from the moon
Sweet Dreams Tomorrow
Time machine from past
现在,当我对关键字进行搜索查询时,请说'celeste from'然后它会显示我想要的东西,即来自月球的Celeste。但是,如果我将查询更改为“celeste the moon”,则表明我没有结果。
这是我的查询脚本
if(!empty($_REQUEST['string']))
{
$search_string = " title LIKE %".mysql_real_escape_string($_REQUEST["string"])."%'";
$query = mysql_query("SELECT * FROM products WHERE ".$search_string);
$row = mysql_num_rows($query) or die(mysql_error());
$row = $row;
$cur_page = $_GET['page'];
$cur_page = ($cur_page < 1)? 1 : $cur_page;
$offset = ($cur_page-1)*$per_page;
$pages = ceil($row/$per_page);
$start = (($cur_page - $num_links) > 0) ? ($cur_page - ($num_links - 1)) : 1;
$end = (($cur_page + $num_links) < $pages) ? ($cur_page + $num_links) : $pages;
$res = mysql_query("SELECT * FROM products WHERE ".$search_string." ORDER BY title LIMIT ".$per_page." OFFSET ".$offset);
while($row=mysql_fetch_array($res))
{
include ('include/form.php');
}
}
我尝试了各种方法,但却无法获得理想的结果。
答案 0 :(得分:1)
首先拆分搜索字符串
$words = explode(' ',$_REQUEST['string']);
然后在select
中使用OR运算$query='SELECT * FROM `products` WHERE `title` LIKE ';
foreach($words as $key=> value){
$query.='"%'.$value.'%" OR';
}
$query=rtrim($string, "OR");
$query.='ORDER BY title LIMIT '.$per_page.' OFFSET '.$offset;
include 'include/common.php';
while($row=mysql_fetch_array(mysql_query($query))) {
include ('include/form.php');
}
你使用mysqli而不是mysql函数时间
答案 1 :(得分:0)
问题是您的查询会查找您输入的确切文本。因此,如果您输入Celeste the moon
,它会查找包含该短语的文字。 WHERE x LIKE '%foo bar%'
表示“找到x包含foo bar
的行,但如果在其之前或之后还有其他内容,则可以。
你需要分解它,就像Shidil建议的那样,但你需要逃避查询的每一部分。 Shidil的代码有一些逻辑错误并且不安全。因此,例如(修改,更正,更安全的Shidil代码版本):
$words = explode(' ',$_REQUEST['string']); // split up the input
$query='SELECT * FROM `products` WHERE '; // first part of the query
foreach($words as $key=> value) {
/* Build the WHERE clause
Note that you need `title` LIKE for each term, and each term
needs to be run through mysql_real_escape_string() */
$query.='`title` LIKE "%'.mysql_real_escape_string($value).'%" OR';
}
// Strip the last "OR"
$query=rtrim($string, "OR");
/* You don't show where $per_page or $offset came from.
If they are user input (even a drop-down or something), you MUST
validate them; otherwise, you will have a SQL injection vulnerability */
$query.=' ORDER BY title LIMIT '.$per_page.' OFFSET '.$offset;
include 'include/common.php';
/* don't put mysql_query() in the while(); it will run the query over and over,
but you'll just keep getting the first row over and over */
$result = mysql_query($query);
while($row=mysql_fetch_array($result)) {
include ('include/form.php');
}
正如大家所指出的那样:Don't use mysql_*
; mysql_*
函数已过时,deprecated且不安全。请改用MySQLi
或PDO
。