gpt4 book ai didi

PHP 使用 ORDER BY 查询 MySQL 对数据库项目进行排序

转载 作者:行者123 更新时间:2023-11-29 01:21:43 26 4
gpt4 key购买 nike

我有一个 MySQL 数据库,用于动态填充网页。我正在构建一个 MySQL 查询,它获取存储在名为 products 的表中的一些产品,稍后我可以使用 PHP 在页面上回显这些产品。该表中的列是 idproduct_namepricedescription。我希望用户能够通过单击页面上的相关链接按字母顺序、价格(低-高)等对产品进行排序。这是我到目前为止写的:

// 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");
}
}

页面是 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>

当我第一次加载该页面时,我的所有产品都按 ID 排序显示。但是,当我单击任何链接时,产品会按价格从高到低排序。如果我将页面刷新为 index.php,产品仍按价格从高到低排序 - 它采用的 SQL 查询就是这样。

我该如何解决这个问题?

最佳答案

将if语句的内容=改为==

关于PHP 使用 ORDER BY 查询 MySQL 对数据库项目进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20376315/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com