选择具有特定MySql请求PHP的所有用户

时间:2015-10-29 15:27:55

标签: 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";
    }

}

&GT;

您可以找到与这些选项匹配的用户(不包含All instrumentAll themes

所有内容都存储在MySql数据库中。

但是,当我点击All themesAll instrument时。我想更新我的选择请求。就像我选择All instrumentAll themes一样,我希望显示每个用户。或者如果我选择All instrumentMetal,我想要显示所有听金属和播放任何乐器的用户。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

You can construct your query to be conditional depending on whether $theme and $instrument have values:

$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);

That said, you should look into PDO Prepared Statements and Placeholders, because all this would take is someone to fiddle around with the DOM to perform some MySQL Injection.