我想讓用戶根據名稱,價格等對mysql查詢進行排序。這個下拉菜單讓他們有能力做到這一點,它根據用戶選擇的內容更改「ORDER BY」子句。這是凌晨3點在這裏,我只是不能看出錯誤:我的代碼有什麼問題?
<?php
$sortBy = $_POST['sortBy'];
if ($sortBy) {
$priceLowToHigh = $_POST['price-low-to-high'];
$priceHighToLow = $_POST['price-high-to-low'];
$dateMostRecent = $_POST['date-most-recent'];
$dateOldest = $_POST['date-oldest'];
$alphabeticalOrder = $_POST['alphabetical-order'];
if ($priceLowToHigh) {
$sortOrder = "price ASC";
} elseif ($priceHighToLow) {
$sortOrder = "price DESC";
} elseif ($dateMostRecent) {
$sortOrder = "date DESC";
} elseif ($dateOldest) {
$sortOrder = "date ASC";
} elseif ($alphabeticalOrder) {
$sortOrder = "name ASC";
}
} else {
$sortOrder = "date DESC";
}
?>
<form action="" method="post">
<select name="sortBy" onchange="this.form.submit()">
<option>Sort By</option>
<option value="price-low-to-high">Price (low to high)</option>
<option value="price-high-to-low">Price (high to low)</option>
<option value="date-most-recent">Date (most recent)</option>
<option value="date-oldest">Date (oldest)</option>
<option value="alphabetical-order">Alphabetical Order</option>
</select>
</form>
後來在ORDER BY子句中使用這樣的:
$query = mysql_query("SELECT * FROM products WHERE category = $categoryId ORDER BY $sortOrder");
不應該表單標籤有一個值的行動?像當前頁面的名稱一樣...發佈到哪裏? – 2010-07-03 06:13:49
不一定,因爲默認值是當前頁面。 – spinon 2010-07-03 06:14:14