[英]Using PHP to sort a SQL query from a dropdown table
我有一個使用JOIN連接在一起的表,我想創建一個帶有提交按鈕的表單,允許最終用戶更改他們希望表格被過濾的方式。 排序欄位於我的網頁上,但實際上並沒有做任何事情。 所以我的問題是我需要做什么才能讓排序按鈕工作。
<?php
$sort = @$_POST['order'];
if (($sort)) { // If you Sort it with value of your select options
$query = "SELECT n.firstname, n.middlename, n.lastname, m.title, f.format, t.price, e.series, t.inventory
FROM book_main AS m
JOIN book_author AS n ON n.author_id=m.author_id
JOIN book_title AS t ON t.title_id=m.title_id
JOIN book_format AS f ON f.format_id=m.format_id
LEFT JOIN book_series AS e ON e.series_id=m.series_id
ORDER BY '".$sort."' ASC";
}
else { // else if you do not pass any value from select option will return this
$query = "SELECT n.firstname, n.middlename, n.lastname, m.title, f.format, t.price, e.series, t.inventory
FROM book_main AS m
JOIN book_author AS n ON n.author_id=m.author_id
JOIN book_title AS t ON t.title_id=m.title_id
JOIN book_format AS f ON f.format_id=m.format_id
LEFT JOIN book_series AS e ON e.series_id=m.series_id
ORDER BY n.lastname ASC";
$results = mysql_query($query);
echo $results['order'];
//can I have a couple points for trying so hard haha...
}
?>
<form name="sort" action="" method="post">
<select name="order">
<option value="choose">Make A Selection</option>
<option value='lastname'>Authors Last name</option>
<option value='price'>Price</option>
<option value='inventory'>Inventory</option>
</select>
<input type="submit" value="Sort" />
</form>
要確保$ sort具有select選項中列出的值,您需要進行如下檢查。 沒有回應的原因是,order不是$ results數組的一部分。
訪問結果的唯一方法是使用以下任何一個http://php.net/manual/en/function.mysql-result.php
if(in_array($sort, ['lastname', 'price', 'inventory'])) {
$query = "SELECT n.firstname, n.middlename, n.lastname, m.title, f.format, t.price, e.series, t.inventory
FROM book_main AS m
JOIN book_author AS n ON n.author_id=m.author_id
JOIN book_title AS t ON t.title_id=m.title_id
JOIN book_format AS f ON f.format_id=m.format_id
LEFT JOIN book_series AS e ON e.series_id=m.series_id
ORDER BY $sort ASC";
} else {
$query = "SELECT n.firstname, n.middlename, n.lastname, m.title, f.format, t.price, e.series, t.inventory
FROM book_main AS m
JOIN book_author AS n ON n.author_id=m.author_id
JOIN book_title AS t ON t.title_id=m.title_id
JOIN book_format AS f ON f.format_id=m.format_id
LEFT JOIN book_series AS e ON e.series_id=m.series_id
ORDER BY n.lastname ASC";
}
$results = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['middlename'];
echo $row['lastname'];
echo $row['title'];
echo $row['format'];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.