简体   繁体   English

PHP使用下拉框排序

[英]PHP Sort by using drop-down box

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). 我需要找到一种使用PHP创建下拉框的方法,该框可以按型号,品牌,屏幕尺寸等对电话进行排序。(我的SQL数据库中已经包含了字段)。 What is the simplest way of going about this? 最简单的方法是什么? I am quite new to PHP and not too sure how to go about it. 我对PHP还是很陌生,不太确定如何去做。

You handle sorting in your MySQL queries: 您可以在MySQL查询中处理排序:

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. 您无法通过javascript(用户端)对查询进行重新排序,因为该查询称为服务器端。

You can use $_GET variables to achieve that. 您可以使用$_GET变量来实现。 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! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM