dongtan8979 2018-08-12 14:04
浏览 44
已采纳

PHP搜索显示的重复结果与查询完全不同

So I'm just trying to create a basic search bar to increase my php and mysql knowledge but I am seriously confused.

I have followed a tutorial and played around with the code myself but I am at a loss the search query kind of works it will display results but the results displayed are nothing like the search query it is displaying many duplicate results.

I have 2 different people with 2 different products linking to them and this is what it is showing.

enter image description here

And here is the query that I am searching.

enter image description here

and here is my code and I'm hoping someone with more knowledge might be able to help out, hoping its not just a simple mistake that I've made :O

<?php
$query = $_GET['q'];
// gets value sent over search form

$min_length = 3;
// you can set minimum length of the query if you want

if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then

    $query = htmlspecialchars($query);
    // changes characters used in html to their equivalents, for example: < to &gt;

    $query = mysql_real_escape_string($query);
    // makes sure nobody uses SQL injection

    $raw_results = DB::query("SELECT  * FROM forsale, users WHERE forsale.productname LIKE '%" . $query .  "%' OR users.username LIKE '%" . $query ."%'");

    if (count($raw_results) > 0) {
      foreach($raw_results as $results) {

        echo $results['productname'];
        echo $results['username'];
        echo $results['price'];

      }
    }else{ // if there is no matching rows do following
        echo "No results";
      }
}else{ // if query length is less than minimum
  echo "Minimum length is ".$min_length;
}

?>

Thank you very much in advance.

  • 写回答

2条回答 默认 最新

  • duanjue7508 2018-08-12 14:11
    关注

    As a quick fix to check if it works, you need to link the two tables together using the user_id...

    $raw_results = DB::query("SELECT  * 
                               FROM forsale, users 
                               WHERE forsale.user_id = users.user_id
                                   and (forsale.productname LIKE '%" . $query .  "%' 
                                     OR users.username LIKE '%" . $query ."%'"));
    

    I would like to recommend moving to the newer JOIN format (https://dev.mysql.com/doc/refman/8.0/en/join.html) as well as looking into using prepared statements and bind variables.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Python程序,深度学习,有偿私
  • ¥15 扫描枪扫条形码出现问题
  • ¥15 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开