首页 > 解决方案 > 在多表列中具有多个术语的简单 PHP 过滤器

问题描述

我正在尝试实现一个搜索过滤器,该过滤器从 mysql 获取数据并应用多个条件,例如从多个表的列中选择和匹配用户。我想通过多个关键字在这些列中搜索,例如来自特定国家或城市且对音乐感兴趣的用户。

我想用大约 10 个表和它的列来实现这个

这是 3 个结构化表格结构的示例

Table User Profile (Main table)

ID | PID | Name | Email | Avatar

1 | 22 |  John | x@x.x | URL
---------------------------------
Table User details

ID | PID | Country | City | Address | HPhone | MPhone

1 |  22 |  Norway |  Bergenv addrews | 2222 |   2222 |
---------------------------------
Table User Interests

ID | PID | Interest | Type | Keyword

1 |  22 |  music | music | pop
---------------------------------
Printed Results format

PID, Name, Avatar

第一个 PHP 文件 file1.php

    <form class="user_search_form" action="file2.php" method="post"> 
    <select class="Interest_types" name="Interest" id="Interest">
    <option value="Retail">Music</option>      
    <option value="Transportation">Movies</option>      
    </select>   

    <select name="city" class="select_city">
    <option value="">City</option>
    <option value="">London</option>
    <option value="">New York</option>
    <option value="">Paris</option>
    </select>

    <input type="submit" value="search"  class="search_btn" />  
    </form>

当前第二个 php 文件 files2.php

    //Limit our results within a specified range.
    $results = $mysqli->prepare("SELECT PID, Name, Avatar FROM Profile");
    $results->execute(); //Execute prepared Query
    $results->bind_result($PID, $Name, $Email, $$Avatar); //bind variables to prepared statement

    //Display records fetched from database.
    echo '<ul class="contents">';
    while($results->fetch()){ //fetch values
        echo "<a href=\"/Profile.php?id=$PID\" onClick='Loading()'><li class=\"userlistitem\">";
        echo  "<img src='$Avatar' height='100' width='100' onerror=\"this.src = '/assets/img/noImg.png'\"/>";
        echo  "$Name  $Email $PasswordD";
        echo "</li></a>";
    }
    echo '</ul>';

files2.php 中最好的 php 格式应该是什么?

非常需要和感谢您的帮助。

标签: javascriptphphtmlmysqlsql

解决方案


您可以使用 mysql 中的连接从这些表中选择您需要的所有数据。一个例子是这样的:

SELECT up.PID, up.Name, up.Avatar FROM User Profile AS up
LEFT JOIN User Details AS ud ON ud.PID = up.PID
LEFT JOIN User Interests AS ui ON ui.PID = up.PID
WHERE ui.KeyWord = 'pop' AND ud.City = 'Bergenv'
ORDER BY up.Name ASC
LIMIT 10

然后只需添加尽可能多的连接即可过滤表。但是请注意不要在没有适当过滤的情况下添加很多,因为如果您需要连接多个包含数百行的表,它会减慢您的页面速度。因此,请仔细计划您的查询。


推荐阅读