根据下拉列表中选定的过滤器列出数据库值

时间:2013-12-06 17:42:00

标签: php mysql database filtering

如何过滤下拉列表选项以列出我的表格条目?

HTML过滤器示例:

<form action="filter.php" method="post">
  <select name="filter">
    <option>FILTER:</option>
    <option value="alphabetical">ASC</option>
    <option value="date">Date</option>
  </select>
</form>

基本MySQL选择:

SELECT * FROM table ORDER BY name

列出值的基本HTML:

echo '<h1>'.$name.'</h1>
      <h1>'.$date.'</h1>';

第二个过滤器(日期)应该执行SELECT,列出所有具有ASC日期的条目。第二个第一个(按字母顺序排列)应该执行一个SELECT,它仅列出ASC的所有名称条目。

知道MySQL SELECT在这种情况下如何工作?

3 个答案:

答案 0 :(得分:2)

HTML:

<select name="filter" onchange="filter(this.value)">
  <option>FILTER:</option>
  <option value="alphabetical">ASC</option> 
  <option value="date">Date</option> 
</select>
<div id="results"></div>// store the results here

的Jquery:

function filter(item){
$.ajax({
type: "POST",
url: "filter.php",
data: { value: item},
success:function(data){
  $("#results").html(data);
}
});
}

filter.php:

include "connection.php";  //database connection
$fieldname = $_POST['value'];
 if($fieldname=="alphabetical"){
  // if you choose first option
  $query1 = mysqli_query("SELECT * FROM table ORDER BY name ASC"); 
  // echo the results
  }else{
  // if you choose second option
  $query1 = mysqli_query("SELECT * FROM table ORDER BY date ASC");
  // echo the results
}

注意:不要忘记包含jquery库。

答案 1 :(得分:0)

这些应该有效,假设名称和日期是表格中的字段名称。

SELECT * FROM table ORDER BY name ASC
SELECT * FROM table ORDER BY date ASC

答案 2 :(得分:0)

我会做这样的事情,

HTML:

<form action="filter.php" method="post">
  <select name="filter">
    <option>FILTER:</option>
    <option value="alphabetical">ASC</option>
    <option value="date">Date</option>
  </select>
</form>

PHP

<?php
    switch($_POST['filter']){
        case "alphabetical":
           $field = "name";
           break 1;
        case "date":
           $field = "date";
           break 1;
    }

 $mysqli = new mysqli("localhost", "my_user", "my_password", "world");
 $stmt = $mysqli->prepare("SELECT * FROM table ORDER BY ? ASC");
 $stmt->bind_params("s",$field);
 $stmt->execute();

 //ETC
?>