如何在php中搜索mysql中的多个单词

时间:2015-05-19 17:09:16

标签: php mysql

在我的代码中,当输入" word 1,word2"等查询时,我无法搜索值。在搜索框中。我的问题是它没有显示任何内容。

这是我的代码:

<?php
include("config.php");

?>
<html>
<body>
<form method="post" action="">
<input type="text" name="q" /> <input type="submit" value=" Search " />
</form>
<?php 
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$q=explode(',',$_POST['q']);
$q1=$q[0];
$q2=$q[1];
$q3=$q[2];
$q=mysql_escape_string($q);
$q_fix=str_replace(" ","%",$q); // Space replacing with %
$sql=mysql_query("SELECT title FROM articles WHERE title LIKE N'%$q_fix%'");

while($row=mysql_fetch_array($sql))
{
//$title=$row['title'];
//echo '<div>'.$title.'</div>';
echo $row['title'].'<br/>';
}

}


?>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

使用您的查询构造,不可能。使用LIKE和可以在任何位置的多个单词,您必须分开:

WHERE title LIKE '%word1%' AND LIKE '%word2%' AND ...

这种搜索非常低效 - 数据库根本无法使用索引。你最好使用fulltext索引。

使用您的构造WHERE title LIKE '%foo bar%',您需要确切的短语foo bar位于该字段中的某个位置。 MySQL不会分别对foobar进行拆分。因此,如果您的字段包含foo baz bar,则您将无法匹配任何内容。

答案 1 :(得分:0)

尝试类似:

$sql="SELECT title FROM articles WHERE title";
foreach($q as $word) {
    if (!empty($word)) {
        $q_fix = str_replace(" ","%",$word);
        $sql .= " LIKE N'%{$word}%' OR";
    }
}
$sql = rtrim($sql, 'OR ');
print_r($sql);

答案 2 :(得分:0)

由于只有名为q的输入:

<input type="text" name="q" /> 

因此,以下内容将访问$_POST键值数组,然后调用explode()

<?php 
$delimiter = ',';    

// validations, set value if exists otherwise null for evaluation 
$q = isset($_POST['q']) ? $_POST['q'] : null;

// null or check for empty string for early termination
if(!$q) {
  // TODO: handle error
  die();
}

// not null, assuming it is comma separated, validations done after  
$q = explode($delimiter, $q);

// validations ie. explode() returns FALSE, [] or [ .., .. ] so:
if(!$q or !is_array($q) or count($q) <= 0) {
  // TODO: handle error
  die();
} 

// some examples to prevent sql injection, xss, 
// omitting implementation of sanitize()
// refer to docs for purpose of each for different security preventions
// mysql_escape_string(), html_entities(), stripslashes(), trim();

$sanitised_array = sanitise($q);

// build query string while sanitizing inputs
// *Note: that LIKE is probably best avoided in this case for
// performance reasons given 'n' inputs ( although we know 'n' is small in this context ). 
// references are below, use IN ( slightly better ) instead

$sql_string = "SELECT title FROM articles WHERE title IN ($sanitised_array)";

// execute query
$result = mysql_query($sql_string);
if (!$result) {
  die('ERROR[BAD]: ' . mysql_error());
}

// mysql_fetch_array — Fetch a result row as an associative array,
// a numeric array, or both

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
  // validations
  if($row == null or !isset($row['title'])) {
    // TODO: log error  
    continue;
  }

  // *htmlentities()
  echo $row['title'].'<br/>';
}


?>

的参考文献:

  1. MySQL IN
  2. Why we do validations and sanitise user inputs
  3. PHP Data Filtering
  4. Database optimisations for LIKE, IN etc in another post
  5. Article for further DB readings
  6. mysql_query() - 请注意弃用通知,请改用mysqli_query()
  7. 希望这有帮助。