Listing database values according to the selected filter in dropdown

database, filtering, mysql, php

Solution

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
}

Note: Do not forget to include jquery library.

Problem

How do I filter dropdown options to list my table entries? HTML filter example: ``` <form action="filter.php" method="post"> <select name="filter"> <option>FILTER:</option> <option value="alphabetical">ASC</option> <option value="date">Date</option> </select> </form> ``` Basic MySQL select: ``` SELECT * FROM table ORDER BY name ``` Basic HTML that lists values: ``` echo '<h1>'.$name.'</h1> <h1>'.$date.'</h1>'; ``` The second filter (date) should do a SELECT that lists all the entries with ASC dates. The second first one (alphabetical) should do a SELECT that lists all the name's entries by ASC only. Any idea of how the MySQL SELECT would work in that case?

Original source