title: PHP sorting database items with ORDER BY query MySQL
body: <p>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 <code>products</code> that I can later echo out on the page with PHP. The columns in that table are <code>id</code>, <code>product_name</code>, <code>price</code> and <code>description</code>. 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:</p>
  
  <pre><code>// 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");
    }
  }
  </code></pre>
  
  <p>The page is <code>index.php</code>, and these are the links in the HTML:</p>
  
  <pre><code>&lt;p&gt;&lt;a href="index.php?sortby=pricehilo"&gt;Price (Highest-Lowest)&lt;/a&gt;&lt;/p&gt;
  &lt;p&gt;&lt;a href="index.php?sortby=pricelohi"&gt;Price (Lowest-Highest)&lt;/a&gt;&lt;/p&gt;
  &lt;p&gt;&lt;a href="index.php?sortby=name"&gt;Alphabetical&lt;/a&gt;&lt;/p&gt;
  </code></pre>
  
  <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.</p>
  
  <p>How can I fix this?</p>