"drop down menu to sort query results on a php page" Code Answer


no, it's easier to keep this as a single script and just allow for the sorting variable to be switched. for security's sake, it's best to limit the user input to a per-defined set of options in the php script:

$sort_options = array('name asc','name desc','dateadded asc','dateadded desc');
   $_get['field'] = 'name';
if (!isset($_get['order'])){
   $_get['order'] = 'asc';

$full_query_sort = $_get['field'].' '.$_get['order'];
if (!in_array($full_query_sort,$sort_options)){
   die('invalid selection');

mysql_select_db($database_connbhn, $connbhn);
$query_rsmarket = "select * from my_items where active=1 order by ".$full_query_sort;
$rsmarket = mysql_query($query_rsmarket, $connbhn) or die(mysql_error());
$row_rsmarket = mysql_fetch_assoc($rsmarket);
$totalrows_rsmarket = mysql_num_rows($rsmarket);

now you can just have the order set with _get variables: http://example.com/page.php?field=name&order=desc etc. this can be set with javascript (or on form submission) using dropdowns:

<select id='field_select' 
      <option value='name' <?php if(!isset($_get['field']) || $_get['field']=='name'){echo "selected";} ?>>sort by name</option>
      <option value='dateadded' <?php if(isset($_get['field']) && $_get['field']=='dateadded'){echo "selected";} ?>>sort by date added</option>

<select id='order_select' 
      <option value='asc' <?php if(!isset($_get['order']) || $_get['order']=='asc'){echo "selected";} ?>>ascending/option>
      <option value='desc' <?php if(isset($_get['order']) && $_get['order']=='desc'){echo "selected";} ?>>decending</option>
By Tom Sebastian on September 2 2022

Answers related to “drop down menu to sort query results on a php page”

Only authorized users can answer the Search term. Please sign in first, or register a free account.