2015-10-29 67 views
2

我在PHP中編寫了一個功能,它是一個搜索引擎。選擇具有特定MySql請求的所有用戶PHP

<form action="result" method="POST"> 
 
    <select name="instrument" id="instrument"> 
 
    <option value="all">All instrument</option> 
 
    <option value="1">Guitar</option> 
 
    <option value="2">Bass</option> 
 
    <option value="3">Battery</option> 
 
    <option value="4">Singer</option> 
 
    </select> 
 
    <select name="theme" id="theme"> 
 
    <option value="all">All themes</option> 
 
    <option value="1">Metal</option> 
 
    <option value="2">Jazz</option> 
 
    <option value="3">Rock</option> 
 
    <option value="4">Blues</option> 
 
    </select> 
 
    <input type="submit" value="search" /> 
 
</form>

我已經這樣的代碼這樣的搜索引擎,它的工作原理

<?php 


if(isset($_POST)) { 

    $theme = $_POST['theme']; 
    $instrument = $_POST['instrument']; 


    $req_search = $bdd->query("SELECT * FROM user,theme,instrument WHERE theme.theme_id = user.user_theme AND instrument.instrument_id = user.user_instrument AND theme_id =".$theme." AND instrument_id =".$instrument); 

    if($req_search->rowCount()>0) { 

    while($search = $req_search->fetch()) { 

     ?> 

     <p><?php echo $search['user_username']; ?></p> 

    <?php 

    } 

    $req_search->closeCursor(); 

    } else { 
     echo "Users not found"; 
    } 

} 

?>

你可以找到誰與這些選項匹配的用戶(不All instrument and All themes

所有內容都存儲在MySql數據庫中。

但是,當我點擊All themesAll instrument。我想更新我的選擇請求。如果我選擇All instrumentAll themes我想顯示每個用戶。或者如果我選擇All instrumentMetal,我想要顯示所有聽金屬和玩任何樂器的用戶。

感謝您的幫助!

+0

我會建議做一個有條件的WHERE語句。如果選擇「不全部」,則使用WHERE語句創建SQL。這將返回所有結果。 – Twisty

回答

0

您可以構建您的查詢,具體取決於是否$theme$instrument具有值是有條件的:

$query = "SELECT * FROM user,theme,instrument 
    WHERE theme.theme_id = user.user_theme 
    AND instrument.instrument_id = user.user_instrument". 
    ($theme!="" ? " AND theme_id='$theme'" : ""). 
    ($instrument!="" ? " AND instrument_id='$instrument'" : ""); 

$req_search = $bdd->query($query); 

這就是說,你應該看看PDO Prepared StatementsPlaceholders,因爲這一切都將需要的是有人擺弄DOM執行一些MySQL注入。