-1

I am basically creating a website and it is a site that sells mobile phones. I need to find a way using PHP to create a drop-down box that can sort the phones by model, brand, screen size etc. (Fields already in my SQL database). What is the simplest way of going about this? I am quite new to PHP and not too sure how to go about it.

user2052241
  • 81
  • 3
  • 11
  • 4
    [what have you tried?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – Pedro del Sol Jan 15 '13 at 17:01
  • Are you using PHP-GTK or what do you mean by "using PHP to create a drop-down box"? – feeela Jan 15 '13 at 17:03
  • I have data in a database table via PHPMyAdmin and I have a site that displays this data. However, I need to create a drop-down box that can sort the products shown by brand, price (ascending/descending) etc. – user2052241 Jan 15 '13 at 17:06

2 Answers2

2

You handle sorting in your MySQL queries:

SELECT * FROM <<table>> ORDER BY 'Brand' DESC

and then call the results in your page; you can't re-order the query via javascript (user-side) since the query is called server-side.

sfell77
  • 976
  • 1
  • 9
  • 15
1

You can use $_GET variables to achieve that. Something like this

<?php
  // Let's say that my products category is a $_GET variable
  $category_id = isset($_GET['category_id']) && is_numeric($_GET['category_id']) ? $_GET['category_id'] : 1; // where 1 is a default category to show!
?>

<select onchange="if(this.value != '') document.location = '/my-phones-category.php?category_id=<?php echo $category_id; ?>&order_by=' + this.value">
  <option value="">Choose an option</option>
  <option value="model"<?php if(isset($_GET['order_by']) && $_GET['order_by'] == 'model') echo ' selected="selected"'; ?>>Model</option>
  <option value="brand"<?php if(isset($_GET['order_by']) && $_GET['order_by'] == 'brand') echo ' selected="selected"'; ?>>Brand</option>
</select>

Then we have to see how we can make our query to add the right order

<?php
  switch($_GET['order_by']) {
    case 'model':
      $order_by = " ORDER BY products.product_model";
      break;
    case 'brand':
      $order_by = " ORDER BY products.product_brand";
      break;
    default:
      $order_by = " ORDER BY products.product_price";
  }

  // Now we have the order and we can make the query

  $sql = $mysqli->query("SELECT product_name, product_price 
                         FROM products
                         WHERE category_id='" . $category_id . "'
                         $order_by");
?>

Good luck!

Mihai Matei
  • 24,166
  • 5
  • 32
  • 50