Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP sorting database items with ORDER BY query MySQL

I have a MySQL database with which I'm dynamically populating a web page. I'm building a MySQL query that fetches some products stored in a table called products that I can later echo out on the page with PHP. The columns in that table are id, product_name, price and description. I want the user to be able to sort products alphabetically, by price (low-high) etc by clicking the relevant links on the page. This is what I've written so far:

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

The page is index.php, and these are the links in the 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>

When I load the page for the first time, all my products are displayed sorted by ID. However, when I click on any link, the products get sorted by price highest to lowest. If I refresh the page as just index.php the products remain sorted by price highest to lowest - the SQL query it is taking is that.

How can I fix this?

like image 935
user2957365 Avatar asked May 14 '26 22:05

user2957365


1 Answers

Change if statement's content = to ==

like image 91
aykut Avatar answered May 17 '26 12:05

aykut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!