0

I'm displaing many items on a page. By default they are sorted by popularity, and I want to allow user to switch between sorting options, also price low to high, high to low.

I came up with this code:

<form action="?" method="GET">
        <select name="sort" id="myselect" onchange="this.form.submit()">
        <option value="pop">Sort by Popularity</option>
        <option value="lh">Sort Low - High</option>
        <option value="hl">Sort by High - Low</option>
    </select>
</form>

So my page will read the sort parameter and do the sorting with SQL, but:

  1. Once user sorted by price for example, the page just refresh and will still display the sort as if it is still by "popular". Is the best practice to change the order of options with PHP, to overcome this?

Otherwise, is this a valid code for my purpose? or is there a smarter way?

EDIT:

I thought about doing the following, but, if I use elseif, I get an error :

PHP Parse error: syntax error, unexpected 'elseif' (T_ELSEIF), expecting end of file

   <form action="?" method="GET">
            <select name="sort" id="select-sorting" onchange="this.form.submit()">

            <?php if ($sorting == 'lh') { ?>
            <option value="lh">Sort by (Low - High)</option>
            <option value="hl">Sort by (High - Low)</option>
            <option value="pop">Sort by Popularity</option>
            <?php }  ?>

            <?php if ($sorting == 'hl') { ?>
            <option value="hl">Sort by (High - Low)</option>
            <option value="lh">Sort by (Low - High)</option>
            <option value="pop">Sort by Popularity</option>
            <?php }  else { ?>

            <option value="pop">Sort by Popularity</option>
            <option value="lh">Sort by (Low - High)</option>
            <option value="hl">Sort by (High - Low)</option>
            <?php } ?>
            </select>
    </form>

And this error happens only because I try to output HTML blocks, if I do for example:

   if ($sorting=='lh'){ echo 'lh-'.$sorting;}
   elseif ($sorting=='hl'){ echo 'hl-'.$sorting;}
   else { echo 'else-'.$sorting;}

same structure works, why?

user8411456
  • 347
  • 1
  • 5
  • 18
  • The code you're showing is just an HTML form. It doesn't sort or display any data. If your data isn't being sorted the way you expect it to, a good place to start would be wherever you sort your data. – David Apr 17 '19 at 15:35
  • try this at top level on same page `` – devpro Apr 17 '19 at 15:36
  • I would leave the sorting to be handled by js. Persist the selected option and use that to sort the results using js. – bos570 Apr 17 '19 at 15:37

3 Answers3

1

You can try a simple way, instead of submitting a form, take a look on the following code snippet

<?php
$sorting = '';
if(isset($_GET['sort'])){
   $sorting = $_GET['sort'];
}
?>
<select name="sort" id="myselect" onchange="sort(this.value);">
    <option value="pop" <?php if($sorting == 'pop'):?>selected="selected"<?php endif;?>>Sort by Popularity</option>
    <option value="lh"  <?php if($sorting == 'lh'):?> selected="selected"<?php endif;?>>Sort Low - High</option>
    <option value="hl"  <?php if($sorting == 'hl'):?> selected="selected"<?php endif;?>>Sort by High - Low</option>
</select>

<script type="text/javascript">
  function sort(option){

   window.location = window.location.pathname+'?sort='+option;
}
</script>

You can get the selected option using $_GET['sort']

Your PHP code should be

if($_GET['sort']){
  switch($_GET['sort']){
      case 'pop': /* ... Your Code..*/
      break;
       case 'lh': /* ... Your Code..*/
       break;
      case 'hl': /* ... Your Code..*/
       break;
      default:
      /* ... Your Code..*/
  }


}
Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
0

First of all I suspect about your refresh is by some window.location or for some redirect. If you can handle the refresh well then I guess you are done.

There are several ways to handle this kind of situation.

  1. You can directly submit the form (without any ajax or javascript) and capture the value of sort by $_GET['sort'] and use the $_GET['sort'] in your SQL query to fetch the desired results. Then you can format the results and print them according to your requirement.

  2. In your form you can add a function to handle the form submission. With that submission handler function you can pass the sort parameter value in ajax request. Your php code will process the request like the way 1. and return the results. After getting the results from your php code your ajax success callback should place the result in the appropriate html. For example, $('#yourplace').html(results);

Hope this helps.

moyeen52
  • 425
  • 3
  • 13
0

There's probably a better way of doing this, but this is how I currently do filtering with my webapps:

index.php

<?php
  $filter = isset($_GET['sort']) ? $_GET['sort'] : false;
  $popNum = 5; // minimum amount of occurences to be considered 'popular'
  # prepare query
  $query = "SELECT * FROM `table_name`";
  switch ($filter) {
    case 'pop':
      $query = "SELECT item, item_price item_description COUNT(*) FROM `table_name` GROUP BY item
          HAVING COUNT(*) > '$popNum' ORDER BY COUNT(*) DESC"; // most popular on top
      break;
    case 'lh':
      $query .= " ORDER BY item_price ASC"; // low to high
      break;
    case 'hl':
      $query .= " ORDER BY item_price DESC"; // high to low
      break;
  }
  // echo $query; // toggle to debug
?>

<form action="<?=$_SERVER['REQUEST_URI'];?>" method="GET">
        <select name="sort" id="myselect" onchange="this.form.submit()">
        <option value="pop"<?=$filter == 'pop' ? ' selected' : false ?>>Sort by Popularity</option>
        <option value="lh"<?=$filter == 'lh' ? ' selected' : false ?>>Sort Low - High</option>
        <option value="hl"<?=$filter == 'hl' ? ' selected' : false ?>>Sort by High - Low</option>
    </select>
    <button onclick="window.location.replace('/index.php');">Reset</button>
</form>

Then execute the query with your choice of API (PDO, MySQLi)...

Kam
  • 116
  • 1
  • 7