我如何对使用MYSQL过滤的类别进行排序?

时间:2017-04-15 21:28:01

标签: php mysql

  

我如何对使用MYSQL过滤的类别进行排序?   例如,我想得到最便宜的帽子。我该怎么做?

 if(isset($_GET['category'])){
        $category = $_GET['category'];
        $sql = "SELECT * FROM store WHERE category='$category'";}else{
        $sql = "SELECT id,title,image FROM store";
    }
    if(isset($_GET['category'],$_GET['value'])){
        $currentPage = $_GET['category'];
        $value = $_GET['value'];
        $sql = "SELECT * FROM store WHERE category='$category'ORDER BY $value";
    }
    if(isset($_GET['value'])) {
        if($_GET['value'] == 'price') {
            // query to get all by price 
            $sql = "SELECT * FROM store ORDER BY price";  
        }  
        elseif($_GET['value'] == 'title') {  
            // query to get all by title
            $sql = "SELECT * FROM store ORDER BY title";  
        } elseif($_GET['value']== 'date') {  
            // query to get all by date added
            $sql = "SELECT * FROM store ORDER BY date_added";  
        }

`

<div id="filters">
		<a href="stores.php">All</a>	
        <a href="stores.php?category=t-shirt">T-Shirt</a>
        <a href="stores.php?category=mug">Mug</a>
        <a href="stores.php?category=hat">Hat</a>
	</div>
	<label for="sort">Sort By</label>
	<select name="sort">
	<option value="price">Price: Low to High</option>
	<option value="title">Title: A-Z</option>
	<option value="date">Newest</option>
	</select>

1 个答案:

答案 0 :(得分:0)

/ *****
在我看来,我看不出你如何通过使用给定的HTML获得你想要的东西。所以我所做的是将类别和排序作为表单输入。通过这种方式,我们可以轻松地操作类别和排序。

这里的表单方法是GET。 POST意味着if(isset($ _ POST))。

希望这有帮助。
****** /
//定义类别
如果(isset($ _ GET [ '类别'])){

$ category = $ _GET ['category'];

}

//定义结果的顺序
如果(isset($ _ GET [ '排序'])){

$ sort = $ _GET ['sort'];

}

//表格提交时 如果(isset($ _ GET [ '提交'])){

//根据类别输入和基于排序输入的订单结果进行选择
$ sql =“SELECT * FROM store WHERE category ='$ category'ORDER BY $ sort”;

}

&lt; forrm action =“store.php”method =“GET”&gt;

&lt; label for =“category”&gt; Category&lt; / label&gt;
    &lt; select name =“category”&gt;
        &lt; option value =“t-shirt”&gt; T恤&lt; / option&gt;
        &lt; option value =“mug”&gt; Mug&lt; / option&gt;
        &lt; option value =“hat”&gt; Hat&lt; / option&gt;
    &LT; /选择&GT;

<label for="sort">Sort By</label>
<select name="sort">
<option value="price">Price: Low to High</option>
<option value="title">Title: A-Z</option>
<option value="date">Newest</option>
</select>

&lt; input type ='submit'name ='submit'/&gt;

&LT; /形式&GT;