PHP关键字搜索重复&结果不正确

时间:2015-05-12 12:39:59

标签: php mysql

当我只搜索一个表但尝试添加两个表时,简单搜索就有效了。现在它返回数据库中的所有行,无论它们是否包含搜索的关键字,每行输出两次。

if(isset($_GET['keywords'])):
$keywords = $db->real_escape_string($_GET['keywords']);
$sql = "
SELECT p.topic, s.title
FROM table_posts p, table_sheets s
WHERE p.topic LIKE '%{$keywords}%'
OR s.title LIKE '%{$keywords}%'
";
$query = $db->query($sql);

?>
  <div class="result-count">
    <p>Found <?php echo $query->num_rows; ?> results.</p><br>
  </div>
<?php

if($query->num_rows):
while($row = $query->fetch_object()):
  $weight = substr_count(strtoupper($row->topic), strtoupper($keywords));
?>
  <div class="result">
    <a href="#"><?php echo $weight . ' ' . $row->topic; ?></a>
  </div>
  <br>
<?php
  endwhile;
 endif;
endif;

返回类似于关键字的内容:

  

1行1数据
  1行1数据
  0行2数据
  0行2数据
  1行3数据
  1行3数据
  ...

2 个答案:

答案 0 :(得分:0)

在获取之前忘记写$query->execute();

答案 1 :(得分:0)

这两个表之间应该有一些关系。所以只有它检索正确的输出。查询应该像......

$sql = "SELECT p.topic, s.title 
FROM table_posts p, table_sheets s 
WHERE p.topic   LIKE '%{$keywords}%' OR s.title LIKE '%{$keywords}%'
AND p.SOME_ID_LIKE_id = s.SOME_RELATED_ID_LIKE_topic_id
";

或者你使用UNION来检索数据