i'm looking to pull back some results from my DB and then the user can click a sort by button to decide whether its ASC or DESC..I've researched some other responses on here and looked at 'usort' but nothing seems to relate to my code. Maybe its because mines pretty basic.
My PHP looks like:
if($_GET['sort_by'] == "pricelow") {
$vehicle_list_query .= " ORDER BY vehicle.price ASC"; } else if($_GET['sort_by'] == "pricehigh") {
$vehicle_list_query .= " ORDER BY vehicle.price DESC"; }
My code looks like:
<select name="sort_by">
<option selected="selected">Sort by:</option>
<option value="pricelow" <?php if (!(strcmp("pricelow", $vehicle_list_query))) {echo "selected=\"selected\"";} ?>>Low</option>
<option value="pricehigh" <?php if (!(strcmp("pricehigh", $vehicle_list_query))) {echo "selected=\"selected\"";} ?>>High</option>
</select>
Hopefully this is quite clear, any information on the subject or links will be most helpful. Cheers guys
<?php
if($_GET['sort_by'] == "pricelow") {
$vehicle_list_query .= " ORDER BY vehicle.price ASC";
} else if($_GET['sort_by'] == "pricehigh") {
$vehicle_list_query .= " ORDER BY vehicle.price DESC";
}
?>
<select name="sort_by">
<option <?php if(!isset($_GET['sort_by'])) { echo"selected=\"selected\"" } ?>>Sort by:</option>
<option value="pricelow" name="pricelow" <?php if($_GET['sort_by'] == "pricelow") { echo "selected=\"selected\"";} ?>>Low</option>
<option value="pricehigh" name="pricehigh" <?php if($_GET['sort_by'] == "pricehigh") { echo "selected=\"selected\"";} ?>>High</option>
</select>
This should work.. Can you show us the rest of the $vehicle_list_query
?
You may re-written your code as,
<select name="sort_by">
<option selected="selected">Sort by:</option>
<option value="asc" <?php if (!(strcmp("asc", $vehicle_list_query))) {echo "selected=\"selected\"";} ?>>Low</option>
<option value="desc" <?php if (!(strcmp("desc", $vehicle_list_query))) {echo "selected=\"selected\"";} ?>>High</option>
</select>
PHP:
<?php
if(isset($_GET['sort_by'])) {
$vehicle_list_query .= " ORDER BY vehicle.price $_GET['sort_by']";
}
?>
Your code looks good so far. It could be a bit shorten but what you have should work. Now you just need to display the results:
$sqllink = mysqli_connect("db","user","password","database");
$result = mysqli_query($sqllink, $vehicle_list_query;
while ($row = mysqli_fetch_assoc($result)
{
echo "<tr>";
echo "<td"> . $row['car_name_column'] . "</td">;
echo "<td>" . $row['car_price_variable'] . "</td>";
echo "</tr>";
}
mysqli_close($sqllink);