1

I've taken an answer from a similar question on this site:

PHP Sort by using drop-down box

and adapted it to my needs but have come stuck on creating a drop down menu to sort products by.

My form code is:

<form name="myform">
        <select name="order_by" onchange="if(this.value != '') document.location = '/equipment.php?cat=<?= $prodCategory;?>&subCat=<?=$subCategory;?>&order_by=' + this.value">
            <option<?php if(isset($_GET['order_by']) && $_GET['order_by'] == 'choose') echo ' selected="selected"'; ?> value="choose">Sort By</option>
            <option<?php if(isset($_GET['order_by']) && $_GET['order_by'] == 'name') echo ' selected="selected"'; ?> value="name">Name</option>
            <option<?php if(isset($_GET['order_by']) && $_GET['order_by'] == 'price') echo ' selected="selected"'; ?> value="price">Price</option>
        </select>
</form>

and my switch statement and query look like this:

 switch($_GET['order_by']) {
            case 'name':
              $order_by = " ORDER BY shortDescription ASC";
              break;
            case 'price':
              $order_by = " ORDER BY rrp ASC";
              break;
          }
        $productQuery = 'SELECT * FROM ********* WHERE subCategory = "' . $subCat[0]['categoryID'] . $order_by . '"';

But for some reason its not sorting them by either of the selections if i choose them.

can someone see any problems with my code?

Community
  • 1
  • 1
Kevlar
  • 344
  • 1
  • 7
  • 25

2 Answers2

2

This is because you have a syntax error. You are not closing quote ' after subCategory value.

$productQuery = 'SELECT * FROM ********* WHERE subCategory = "' . $subCat[0]['categoryID'] . $order_by . '"';
                                                                                         //^ here 

So change quotes with double quotes and concatenate correctly to fix your query

$productQuery = "SELECT * FROM ********* WHERE subCategory = '" . $subCat[0]['categoryID'] . "'" .  $order_by;
Fabio
  • 23,183
  • 12
  • 55
  • 64
1

you were required to change the query section and you have got the right answer, while i have another solution for your sorting.

You can sort all you mySQL data using Ajax and PHP. you will not needed to refresh your page in that case. just follow the URL Sorting MySQL data using PHP and Ajax