我试图允许用户根据名称,价格等对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");
答案 0 :(得分:4)
您正在错误地处理菜单。您的$ sortBy变量已经是用户选择的变量,而不是单独的$ _POST字段。
这是你应该做的 -
<?php
$sortBy = $_POST['sortBy'];
if($sortBy == 'price-low-to-high') {
$sortOrder = "price ASC";
} else if($sortBy == 'price-high-to-low') {
$sortOrder = "price DESC";
} else if($sortBy == 'date-most-recent') {
$sortOrder = "date DESC";
} else if($sortBy == 'date-oldest') {
$sortOrder = "date ASC";
} else if($sortBy == 'alphabetical-order') {
$sortOrder = "name ASC";
} else {
$sortOrder = "date DESC";
}
?>
答案 1 :(得分:1)
我无法评论你的回答拉斐尔,因为我不够高,但我只是想提一下可能使用switch语句来提高可读性。但是你就在那里。给予好评
答案 2 :(得分:0)
看起来你的代码是双引号,当它应该是单一的,让php替换你的代码。您应该将该sql打印到屏幕上,您将看到它可能没有替换该值。
我指的是你调用mysql_query的行。
答案 3 :(得分:0)
你的基本代码有点不对劲。它应该如下: -
<?php
$sortBy = $_POST['sortBy'];
if($sortBy == 'price-low-to-high')
$sortOrder = "price ASC";
else if($sortBy == 'price-high-to-low')
$sortOrder = "price DESC";
else if($sortBy == 'date-most-recent')
$sortOrder = "date DESC";
else if($sortBy == 'date-oldest')
$sortOrder = "date ASC";
else if($sortBy == 'alphabetical-order')
$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>
如果您将代码更改为上述代码,我认为现在可以使用。
希望它有所帮助。