查询错误,尝试按关键字进行搜索

时间:2011-12-08 17:23:55

标签: php mysql sql

我有一个变量和一个user_name我想搜索user_name的字符串(function_description)

这是错的:

$function_keywords = mysql_real_escape_string($_POST['function_keywords']);
if($function_keywords=="" || empty($function_keywords)){
    redirect("show.php?functions=PHP");
}
//trim whitespace from the stored variable
$trimmed = trim($function_keywords);
//separate key-phrases into keywords
$trimmed_keywords = explode(" ",$trimmed);
// Build SQL Query for each keyword entered
foreach ($trimmed_keywords as $trimm){
// MySQL "MATCH" is used for full-text searching.
//this code is ebv weird , should check out soon!
$query = "SELECT * 
          FROM functions
          WHERE isEnabled=1 AND isPrivate=0
          AND function_description LIKE '{$trimm}' 
          AND user_name='{$user_name}'   
          ";
 // Execute the query to  get number of rows that contain search kewords
 $results=mysql_query ($query,$connection);

3 个答案:

答案 0 :(得分:2)

就“like”语法而言,你必须使用'%'符号。如果你查询

select * from table where column like '%yourkeyword%'

然后它返回表格列中包含“yourkeyword”的所有行。

只有当列='yourkeyword'

时,您的陈述才会成立

答案 1 :(得分:1)

要查看function_description是否包含您需要使用'%'的关键字,它代表'*'在unix中的作用。试试function_description LIKE'%{$ trimm}%'

答案 2 :(得分:1)

这非常低效。如果有人输入5个关键字,您将运行搜索5次并获得5组结果。从这些方面尝试更多的东西:

$words = $_POST['function_keywords'];
if ($words == '') {
    ... abort ...
}

$parts = trim(explode(' ', $words));
$clauses = array();
foreach($parts as $part) {
    $clauses[] = "function_description LIKE '%" . mysql_real_escape_string($part) . "%'";
}

$clause = implode(' OR ' , $clauses);

$sql = "SELECT .... WHERE (isEnabled=1) AND (isPrivate=1) AND (user_name='$user_name') AND ($clause)";
$result = mysql_query($sql) or die(mysql_error());

这将为指定的每个关键字构建一系列or语句,并将整个事件作为单个查询运行。

相关问题