如何从搜索功能中的两个表中检索数据

时间:2017-10-10 07:39:11

标签: php mysql search

所以我有这个简单的搜索代码

<div id="page">
    <!-- start content -->
<?php

if(isset($_POST['search']))
{
    $valueToSearch = $_POST['valueToSearch'];
    // search in all table columns
    // using concat mysql function
    $query = "SELECT * FROM `pdspersonalinfo` WHERE CONCAT(`personid`, `surname`, `firstname`, `sex`) LIKE '%".$valueToSearch."%'";
    $search_result = filterTable($query);

}
 else {
    $query = "SELECT * FROM `pdspersonalinfo`";
    $search_result = filterTable($query);
}

// function to connect and execute the query
function filterTable($query)
{
    $connect = mysqli_connect("localhost", "root", "", "ucwd");
    $filter_Result = mysqli_query($connect, $query);
    return $filter_Result;
}

?>

<!DOCTYPE html>
<html>
    <head>
        <title>PHP HTML TABLE DATA SEARCH</title>
        <style>
            table,tr,th,td
            {
                border: 1px solid black;
            }
        </style>
    </head>
    <body>

        <form action="searchtrain[orig].php" method="post">
            <input type="text" name="valueToSearch" placeholder="Value To Search" autocomplete="off"><br><br>
            <input type="submit" name="search" value="Filter"><br><br>

            <table bgcolor="#FFFFFF">
                <tr>
                    <th>ID</th>
                    <th>Surame</th>
                    <th>First Name</th>
                    <th>Sex</th>
                    <th>Training</th>
                </tr>

      <!-- populate table from mysql database -->
                <?php while($row = mysqli_fetch_array($search_result)):?>
                <tr>
                    <td><?php echo $row['personid'];?></td>
                    <td><?php echo $row['surname'];?></td>
                    <td><?php echo $row['firstname'];?></td>
                    <td><?php echo $row['sex'];?></td>
                    <td><?php echo $row['traintitle'];?></td>
                </tr>
                <?php endwhile;?>
            </table>
        </form>

    </body>
</html>
</div>

但我希望我的search_results从两个tables的公共列中检索数据

我的第一个表名为pdspersonlinfo,并且包含以下行personid, position, day, month, year, surname, firstname, middlename, sex

我的第二个表名为pdstrain,并且包含以下行personid, trainid, traintitle, trainfrom, trainto

当我搜索名称Jacob时,将检索数据surnamefirstname middlename - traintitle

我是phpmysql的初学者。我希望能理解这一点。

我事先感谢你^ _ ^

2 个答案:

答案 0 :(得分:0)

您需要加入。

%s

答案 1 :(得分:0)

您可以在选择查询

中加入表格
SELECT
I.surname, I.firstname, I.middlename, P.traintitle
FROM pdspersonlinfo I
LEFT JOIN pdstrain P ON P.personid = I.personid
WHERE CONCAT(I.personid, I.surname, I.firstname, I.sex) LIKE '%valueToSearch%'

不要忘记正确转义用户输入的搜索值!