PHP使用ORDERBY查询MySQL对数据库项进行排序


PHP sorting database items with ORDER BY query MySQL

我有一个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语句的内容=更改为==