Filter Prices From Low to High in PHP, MySQL

If you need to filter prices from low to high in PHP & MySQL for your web application. Then This tutorial will be very helpful for you. here,

In this tutorial, the PHP filter price source code is shared with some simple steps and easy explanations that will be very easy to integrate into the project. So, read all the given points without skipping anyone of them.

php filter prices from low to high

Now let’s how works –

The filter price has select options input fields that have two options.

  • The first option is ‘Price low to high
  • The second option is ‘Price high to low

If you need to get the price in the increasing order (low to high price order) then you will have to select the first option ‘price low to high‘ and then click the submit button. After that will get the filtered price in the HTML table

If you need to get the price in the decreasing order (high to low price order) then you will have to select the first option ‘price high to low’ and then click the submit button. After that will get the filtered price in the HTML table

Steps to Filter Price Low to High in PHP, MySQL

Now, Let’s start the coding to filter prices from low to high with the following simple steps –

You can also learn the following examples –

Filter Products By Price In PHP & MySQL

Filter Data With Checkboxes In PHP & MySQL

Filter Data By Category In PHP & MySQL

1. Create a Directory Structure

First of all, You should create the following directory structure to filter prices from low to high.

source-code/
   |__database.php
   |__index.php
   |__filter-price.php
   |__display-price.php
   |

2. Create MySQL Table

Now, Create a MySQL database

CREATE DATABASE codingstatus;

Create a table with the name of the products

CREATE TABLE `products` (
 `id` int(10) NOT NULL AUTO_INCREMENT,
 `productName` varchar(255) DEFAULT NOT NULL,
 `price` int(20) DEFAULT NOT NULL
);

4. Insert Data with Price in Table

Now, You have to insert some data with price into the product table.

INSERT INTO 
  products(id, productName, price)
VALUES
  (1', 'product-1','45'),
  (2', 'product-2','60'),
  (3', 'product-3','70'),
  (4', 'product-4','10'),
  (5', 'product-5','110'),
  (6', 'product-6','80'),
  (7', 'product-7','90'),
  (8', 'product-8','65'),
  (9', 'product-9','4'),
  ('10', 'product-10','120');

3. Setup MySQL Database Connection

Now, You have to connect your PHP to the MySQL database with the following PHP script –

In this script, we have declared the table name in the constant variable to use it globally on any page.

define('productTable', 'products');

File Name – database.php

<?php
define('productTable', 'products');

$hostname     = "localhost";
$username     = "root";
$password     = "";
$databasename = "codingstatus";

$conn = mysqli_connect($hostname, $username, $password, $databasename);

if (!$conn) {
    die("Unable to Connect database: " . mysqli_connect_error());
}
?>

5. Create a Form to filter price

Now, You need to create the price filtering UI by using the following points –

  • Create a basic HTML structure/code
  • Include two files database.php and filter-price.php
  • Create a form with the post method and create the select input field & submit button.
  • Create select input with the name filterPrice and create two options with value priceAsc and priceDesc respectively.
  • Create a submit button with the name of filter
  • Include the file display-data.php just after the form.

File Name – index.php

<?php
include("database.php");
include("filter-price.php");
?>
<form method="post">
<select name="filterPrice">
    <option value="priceAsc"  <?php echo $_POST['filterPrice']=='priceAsc'?'selected':''; ?>>Price Low to High</option>
    <option value="priceDesc" <?php echo $_POST['filterPrice']=='priceDesc'?'selected':''; ?>>Price High to Low</option>
</select>
<input type="submit" name="filter">
</form>


<?php
 include("display-data.php");

?>

6. Filter data by category in PHP

Now, create a price filtering script in PHP with the following points –

  • First, check whether the form is submitted or not to filter the price using $_POST[‘filter’]  within thin the if condition. if the form is submitted then call the function filterPriceData()  and assigned it to the $filterPriceData.
  • Create a custom function filterPriceData() and implement the following points within it
  • Get the filtered price input value using $_POST[‘filterPrice’] and assign it to $filterPrice.
  • Declare $conn with the keyword global to use it globally.
  • If $filterPrice is not empty then write the following points within the if condition.
  • Assign a value ‘DESC’ to the variable $orderby
  • if $filterPrice is equal to the ‘priceAsc’ then assign value ‘ASC’ to the $orderby.
  • Write MySQLi query to select data with a price based on the value of $orderby
  • If recods is greater than zero then get the records with the $result->fetch_all(MYSQLI_ASSOC) and assign it to the $data.
  • After that, return the value of $data .

File Name – filter-price

<?php

if(isset($_POST['filter'])) {
    
    $filterPriceData = filterPriceData();

}


function filterPriceData() {

    $filterPrice = $_POST['filterPrice'];
    global $conn;
    
    $data =[];
    if(!empty($filterPrice)){
         $orderby = 'DESC';
        if($filterPrice == 'priceAsc'){

            $orderby = 'ASC';
        }

        $query = "SELECT productName, price FROM ".productTable;
        $query .= " ORDER BY price ". $orderby;

        $result = $conn->query($query);

        if($result->num_rows > 0) {
          $data = $result->fetch_all(MYSQLI_ASSOC);;
        
        } 
   } 

   return $data;
}

7. Display Data with Price in Table

Follow the following points to display data with the price in the HTML table when the filter price and submit the form.

  • If the value of $filterPriceData is not empty then implement the next all points within it
  • Create the first row of the table with three columns S.N, Product, price
  • Then create other rows dynamically based on the filter price records.
  • Apply the for each loop to the $filterPriceData and print the value of columns ‘productName’ and ‘price’ respectively.

File Name – display-data.php

<?php
if(!empty($filterPriceData)) {
?>
<table border="1" cellspacing="0" cellpadding="5">
    <tr>
        <th>S.N</th>
        <th>Product</th>
        <th>Price</th>
    </tr>
<?php
foreach($filterPriceData as $filterData){
    $sn = 1;
?>
<tr>
    <td><?php echo $sn; ?></td>
    <td><?php echo $filterData['productName']?></td>
    <td><?php echo $filterData['price']?></td>
</tr>
<?php
$sn++; }
?>

</table>
<?php
}

?>

8. Test yourself to filter the Price

After implementing all the given steps, you can now test the PHP price filtering from low to high to open in the web browser.

You will get a select form with two options. first, price low to high, and second, price high to low.

  • When you select the price low to high option and submit the form then the data with price will display in increasing order in the form of a table.
  • When you select the price high to low option and submit the form then the data with price will display in decreasing order in the form of a table.