选择带有范围的下拉列表,然后在数据库中搜索

时间:2018-04-18 09:30:20

标签: php mysql

我是这个领域的新人,所以请不要对我很苛刻。它看起来很简单,但我无法理解。所以,我有下拉选择,如:

<select name="mode" id="mode">
    <option value="None">All</option>
    <option value="300-400">Inside</option>
    <option value="200-299">Outside</option>
</select>

然后我现在有了这个

$cMode=($mode == "None") ? '"%"' : $mode;

SELECT * FROM sections WHERE code LIKE '.$cMode.'

如果我选择Inside在值300和400之间进行搜索,如何更改查询?

3 个答案:

答案 0 :(得分:2)

您可以将if-elseexplode()list()

一起使用
if($mode == "None"){
    $cMode = '"%"';
    SELECT * FROM sections WHERE code LIKE '.$cMode.'
}else{
    list($start,$eand) = explode('-',$mode);
    SELECT * FROM sections WHERE code BETWEEN $start AND $end
}

正如您在评论中所说: -

  $cMode ='';
   if($mode == "None"){
     $cMode = 'LIKE "%"';
   }else{
     list($start,$eand) = explode('-',$mode);
     $cMode ="BETWEEN $start AND $end";
   }

$query = "SELECT * FROM sections WHERE code $cMode";

答案 1 :(得分:1)

您可以使用text条件动态制作$cMode

if and else

有关详细信息SQL BETWEEN Operator

答案 2 :(得分:0)

我还不太了解你的要求,这是我如何使用过滤器从行打印数据的示例

<form action="PAGE.php" method="POST" id="users_selection">
    <select name="mode" id="mode">
        <option value="None">All</option>
        <option value="300-400">Inside</option>
        <option value="200-299">Outside</option>
    </select>
    <input type="submit" value="choose" name="choosing_user">
</form>
<?php
    $servername = "";
    $susername = "";
    $spassword = "";
    $dbname = "";
    $conn = mysqli_connect($servername, $susername, $spassword, $dbname);
    $mode = $_POST['mode'];
    $sql = "SELECT * FROM sections";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $MYSQL_data = $row['data'];
            if($mode=="None"){
                echo '<p>'.$MYSQL_data.'</p>';
            }else if($mode=="300-400"){
                if($MYSQL_data>299 && $MYSQL_data <401){
                    echo '<p>'.$MYSQL_data.'</p>';
                }
            }else if($mode=="200-299"){
                if($MYSQL_data>199 && $MYSQL_data <300){
                    echo '<p>'.$MYSQL_data.'</p>';
                }
            }
        }
    }
?>