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:
- 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?