use*_*365 2 php mysql sql sorting sql-order-by
我有一个MySQL数据库,我正在动态填充网页.我正在构建一个MySQL查询,该查询获取存储在一个表中的一些产品,这些产品products随后可以在PHP页面上回显.在该表中的列id,product_name,price和description.我希望用户能够按字母顺序,按价格(低 - 高)等对产品进行排序,方法是单击页面上的相关链接.这是我到目前为止所写的:
// Run a SELECT query to get all the products stored in the database
// By default, if no sorting URL variable is fed into the page, then the SQL query becomes order by id.
// The first time you land on the index page as plain index.php, not index.php?=variable, this is the query that's used
$sql = mysqli_query($con,"SELECT * FROM products ORDER BY id DESC");
// If the user chooses to sort the produts in a different way, then an HTML link will set a PHP variable into this page
// We will check for that variable and change the SQL query to sort the products in a different way
if (isset($_GET['sortby'])) {
// Capture that in a variable by that name
$sortby = $_GET['sortby'];
// Now to change the SQL query based on the sorting the user chose (price high to low, low to high, alphabetical and latest first)
if ($sortby = 'pricehilo') {
$sql = mysqli_query($con,"SELECT * FROM products ORDER BY price DESC");
}
elseif ($sortby = 'pricelohi') {
$sql = mysqli_query($con,"SELECT * FROM products ORDER BY price ASC");
}
elseif ($sortby = 'name') {
$sql = mysqli_query($con,"SELECT * FROM products ORDER BY product_name");
}
}
Run Code Online (Sandbox Code Playgroud)
页面是index.php,这些是HTML中的链接:
<p><a href="index.php?sortby=pricehilo">Price (Highest-Lowest)</a></p>
<p><a href="index.php?sortby=pricelohi">Price (Lowest-Highest)</a></p>
<p><a href="index.php?sortby=name">Alphabetical</a></p>
Run Code Online (Sandbox Code Playgroud)
当我第一次加载页面时,我的所有产品都按ID排序显示.但是,当我点击任何链接时,产品按价格从最高到最低排序.如果我只是将页面刷新为index.php,那么产品仍按价格从最高到最低排序 - 它所采用的SQL查询就是这样.
我怎样才能解决这个问题?