2017-10-10 105 views
0

所以我有这个简单的搜索代码如何检索搜索功能

<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

当我搜索,例如名字雅各布,数据surnamefirstnamemiddlename - traintitle将被检索

我非常的phpmysql初学者。我希望这可以理解。

我提前感谢您^ _^

+0

听起来像你正在寻找INNER JOIN:https://www.w3resource.com/sql/joins/perform-an-inner-join.php –

回答

0

您需要加入。

SELECT a.something, b.something 
FROM tableA a JOIN tableB b 
ON a.id = b.id 
+0

谢谢弗雷德,我没有格式化它,因为它是一个班轮,所以并不认为这是必要的。 – Chris

0

你可以加入表中的select查询

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%' 

不要忘记正确逃生用户输入搜索值!

+0

我在这部分有错'mysqli_fetch_array($ search_result)'tho – Xenon

+0

你会得到什么错误? – Odyssey1111

+0

没关系,^ _ ^我看到了什么是错的。谢谢 – Xenon