Drop down filter and lateral checkbox filters

Hello everyone,i am new to this site.I am having some problems with my project where i must add a drop down filter based on 3 comboboxes,dependant on each other.Also i want to and an lateral filter for example filter of brands, prices etc, i am calling for help because it’s first time when i use filters.My code is below.Thanks in advance,hope you’ll solve my problem.

product.php

<?php   
 session_start();  
 $connect = mysqli_connect("localhost", "root", "", "test");  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Multi Tab Shopping Cart By Using PHP Ajax Jquery Bootstrap Mysql</title>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
      </head>  
      <body>  
           <br />  
           <div class="container" style="width:800px;">  
                <h3 align="center">Multi Tab Shopping Cart By Using PHP Ajax Jquery Bootstrap Mysql</h3><br />  
                <ul class="nav nav-tabs">  
                     <li class="active"><a data-toggle="tab" href="#products">Product</a></li>  
                     <li><a data-toggle="tab" href="#cart">Cart <span class="badge"><?php if(isset($_SESSION["shopping_cart"])) { echo count($_SESSION["shopping_cart"]); } else { echo '0';}?></span></a></li>  
                </ul>  
                <div class="tab-content">  
                     <div id="products" class="tab-pane fade in active">  
                     <?php  
                     $query = "SELECT * FROM tbl_product ORDER BY id ASC";  
                     $result = mysqli_query($connect, $query);  
                     while($row = mysqli_fetch_array($result))  
                     {  
                     ?>  
                     <div class="col-md-4" style="margin-top:12px;">  
                          <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:350px;" align="center">  
                               <img src="images/<?php echo $row["image"]; ?>" class="img-responsive" /><br />  
                               <h4 class="text-info"><?php echo $row["name"]; ?></h4>  
                               <h4 class="text-danger">$ <?php echo $row["price"]; ?></h4>  
                               <input type="text" name="quantity" id="quantity<?php echo $row["id"]; ?>" class="form-control" value="1" />  
                               <input type="hidden" name="hidden_name" id="name<?php echo $row["id"]; ?>" value="<?php echo $row["name"]; ?>" />  
                               <input type="hidden" name="hidden_price" id="price<?php echo $row["id"]; ?>" value="<?php echo $row["price"]; ?>" />  
                               <input type="button" name="add_to_cart" id="<?php echo $row["id"]; ?>" style="margin-top:5px;" class="btn btn-warning form-control add_to_cart" value="Add to Cart" />  
                          </div>  
                     </div>  
                     <?php  
                     }  
                     ?>  
                     </div>  <div id="cart" class="tab-pane fade">  
                          <div class="table-responsive" id="order_table">  
                               <table class="table table-bordered">  
                                    <tr>  
                                         <th width="40%">Product Name</th>  
                                         <th width="10%">Quantity</th>  
                                         <th width="20%">Price</th>  
                                         <th width="15%">Total</th>  
                                         <th width="5%">Action</th>  
                                    </tr>  
                                    <?php  
                                    if(!empty($_SESSION["shopping_cart"]))  
                                    {  
                                         $total = 0;  
                                         foreach($_SESSION["shopping_cart"] as $keys => $values)  
                                         {                                               
                                    ?>  
                                    <tr>  
                                         <td><?php echo $values["product_name"]; ?></td>  
                                         <td><input type="text" name="quantity[]" id="quantity<?php echo $values["product_id"]; ?>" value="<?php echo $values["product_quantity"]; ?>" data-product_id="<?php echo $values["product_id"]; ?>" class="form-control quantity" /></td>  
                                         <td align="right">$ <?php echo $values["product_price"]; ?></td>  
                                         <td align="right">$ <?php echo number_format($values["product_quantity"] * $values["product_price"], 2); ?></td>  
                                         <td><button name="delete" class="btn btn-danger btn-xs delete" id="<?php echo $values["product_id"]; ?>">Remove</button></td>  
                                    </tr>  
                                    <?php  
                                              $total = $total + ($values["product_quantity"] * $values["product_price"]);  
                                         }  
                                    ?>  
                                    <tr>  
                                         <td colspan="3" align="right">Total</td>  
                                         <td align="right">$ <?php echo number_format($total, 2); ?></td>  
                                         <td></td>  
                                    </tr>  
                                    <tr>  
                                         <td colspan="5" align="center">  
                                              <form method="post" action="cart.php">  
                                                   <input type="submit" name="place_order" class="btn btn-warning" value="Place Order" />  
                                              </form>  
                                         </td>  
                                    </tr>  
                                    <?php  
                                    }  
                                    ?>  
                               </table>  
                          </div>  
                     </div>  
                </div>  
           </div>  
      </body>  
 </html>  
 <script>  
 $(document).ready(function(data){  
      $('.add_to_cart').click(function(){  
           var product_id = $(this).attr("id");  
           var product_name = $('#name'+product_id).val();  
           var product_price = $('#price'+product_id).val();  
           var product_quantity = $('#quantity'+product_id).val();  
           var action = "add";  
           if(product_quantity > 0)  
           {  
                $.ajax({  
                     url:"action.php",  
                     method:"POST",  
                     dataType:"json",  
                     data:{  
                          product_id:product_id,   
                          product_name:product_name,   
                          product_price:product_price,   
                          product_quantity:product_quantity,   
                          action:action  
                     },  
                     success:function(data)  
                     {  
                          $('#order_table').html(data.order_table);  
                          $('.badge').text(data.cart_item);  
                          alert("Product has been Added into Cart");  
                     }  
                });  
           }  
           else  
           {  
                alert("Please Enter Number of Quantity")  
           }  
      });  
      $(document).on('click', '.delete', function(){  
           var product_id = $(this).attr("id");  
           var action = "remove";  
           if(confirm("Are you sure you want to remove this product?"))  
           {  
                $.ajax({  
                     url:"action.php",  
                     method:"POST",  
                     dataType:"json",  
                     data:{product_id:product_id, action:action},  
                     success:function(data){  
                          $('#order_table').html(data.order_table);  
                          $('.badge').text(data.cart_item);  
                     }  
                });  
           }  
           else  
           {  
                return false;  
           }  
      });  
      $(document).on('keyup', '.quantity', function(){  
           var product_id = $(this).data("product_id");  
           var quantity = $(this).val();  
           var action = "quantity_change";  
           if(quantity != '')  
           {  
                $.ajax({  
                     url :"action.php",  
                     method:"POST",  
                     dataType:"json",  
                     data:{product_id:product_id, quantity:quantity, action:action},  
                     success:function(data){  
                          $('#order_table').html(data.order_table);  
                     }  
                });  
           }  
      });  
 });  
 </script>

action.php

<?php  
 //action.php  
 session_start();  
 $connect = mysqli_connect("localhost", "root", "", "test");  
 if(isset($_POST["product_id"]))  
 {  
      $order_table = '';  
      $message = '';  
      if($_POST["action"] == "add")  
      {  
           if(isset($_SESSION["shopping_cart"]))  
           {  
                $is_available = 0;  
                foreach($_SESSION["shopping_cart"] as $keys => $values)  
                {  
                     if($_SESSION["shopping_cart"][$keys]['product_id'] == $_POST["product_id"])  
                     {  
                          $is_available++;  
                          $_SESSION["shopping_cart"][$keys]['product_quantity'] = $_SESSION["shopping_cart"][$keys]['product_quantity'] + $_POST["product_quantity"];  
                     }  
                }  
                if($is_available < 1)  
                {  
                     $item_array = array(  
                          'product_id'               =>     $_POST["product_id"],  
                          'product_name'               =>     $_POST["product_name"],  
                          'product_price'               =>     $_POST["product_price"],  
                          'product_quantity'          =>     $_POST["product_quantity"]  
                     );  
                     $_SESSION["shopping_cart"][] = $item_array;  
                }  
           }  
           else  
           {  
                $item_array = array(  
                     'product_id'               =>     $_POST["product_id"],  
                     'product_name'               =>     $_POST["product_name"],  
                     'product_price'               =>     $_POST["product_price"],  
                     'product_quantity'          =>     $_POST["product_quantity"]  
                );  
                $_SESSION["shopping_cart"][] = $item_array;  
           }  
      }  
      if($_POST["action"] == "remove")  
      {  
           foreach($_SESSION["shopping_cart"] as $keys => $values)  
           {  
                if($values["product_id"] == $_POST["product_id"])  
                {  
                     unset($_SESSION["shopping_cart"][$keys]);  
                     $message = '<label class="text-success">Product Removed</label>';  
                }  
           }  
      }  
      if($_POST["action"] == "quantity_change")  
      {  
           foreach($_SESSION["shopping_cart"] as $keys => $values)  
           {  
                if($_SESSION["shopping_cart"][$keys]['product_id'] == $_POST["product_id"])  
                {  
                     $_SESSION["shopping_cart"][$keys]['product_quantity'] = $_POST["quantity"];  
                }  
           }  
      }  
      $order_table .= '  
           '.$message.'  
           <table class="table table-bordered">  
                <tr>  
                     <th width="40%">Product Name</th>  
                     <th width="10%">Quantity</th>  
                     <th width="20%">Price</th>  
                     <th width="15%">Total</th>  
                     <th width="5%">Action</th>  
                </tr>  
           ';  
      if(!empty($_SESSION["shopping_cart"]))  
      {  
           $total = 0;  
           foreach($_SESSION["shopping_cart"] as $keys => $values)  
           {  
                $order_table .= '  
                     <tr>  
                          <td>'.$values["product_name"].'</td>  
                          <td><input type="text" name="quantity[]" id="quantity'.$values["product_id"].'" value="'.$values["product_quantity"].'" class="form-control quantity" data-product_id="'.$values["product_id"].'" /></td>  
                          <td align="right">$ '.$values["product_price"].'</td>  
                          <td align="right">$ '.number_format($values["product_quantity"] * $values["product_price"], 2).'</td>  
                          <td><button name="delete" class="btn btn-danger btn-xs delete" id="'.$values["product_id"].'">Remove</button></td>  
                     </tr>  
                ';  
                $total = $total + ($values["product_quantity"] * $values["product_price"]);  
           }  
           $order_table .= '  
                <tr>  
                     <td colspan="3" align="right">Total</td>  
                     <td align="right">$ '.number_format($total, 2).'</td>  
                     <td></td>  
                </tr>  
                <tr>  
                     <td colspan="5" align="center">  
                          <form method="post" action="cart.php">  
                               <input type="submit" name="place_order" class="btn btn-warning" value="Place Order" />  
                          </form>  
                     </td>  
                </tr>  
           ';  
      }  
      $order_table .= '</table>';  
      $output = array(  
           'order_table'     =>     $order_table,  
           'cart_item'          =>     count($_SESSION["shopping_cart"])  
      );  
      echo json_encode($output);  
 }  
 ?>

cart.php

<?php  
 //cart.php  
 session_start();  
 $connect = mysqli_connect("localhost", "root", "", "shopping_cart");  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Multi Tab Shopping Cart By Using PHP Ajax Jquery Bootstrap Mysql</title>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
      </head>  
      <body>  
           <br />  
           <div class="container" style="width:800px;">  
                <?php  
                if(isset($_POST["place_order"]))  
                {  
                     $insert_order = "  
                     INSERT INTO tbl_order(customer_id, creation_date, order_status)  
                     VALUES('1', '".date('Y-m-d')."', 'pending')  
                     ";  
                     $order_id = "";  
                     if(mysqli_query($connect, $insert_order))  
                     {  
                          $order_id = mysqli_insert_id($connect);  
                     }  
                     $_SESSION["order_id"] = $order_id;  
                     $order_details = "";  
                     foreach($_SESSION["shopping_cart"] as $keys => $values)  
                     {  
                          $order_details .= "  
                          INSERT INTO tbl_order_details(order_id, product_name, product_price, product_quantity)  
                          VALUES('".$order_id."', '".$values["product_name"]."', '".$values["product_price"]."', '".$values["product_quantity"]."');  
                          ";  
                     }  
                     if(mysqli_multi_query($connect, $order_details))  
                     {  
                          unset($_SESSION["shopping_cart"]);  
                          echo '<script>alert("You have successfully place an order...Thank you")</script>';  
                          echo '<script>window.location.href="cart.php"</script>';  
                     }  
                }  
                if(isset($_SESSION["order_id"]))  
                {  
                     $customer_details = '';  
                     $order_details = '';  
                     $total = 0;  
                     $query = '  
                     SELECT * FROM tbl_order  
                     INNER JOIN tbl_order_details  
                     ON tbl_order_details.order_id = tbl_order.order_id  
                     INNER JOIN tbl_customer  
                     ON tbl_customer.CustomerID = tbl_order.customer_id  
                     WHERE tbl_order.order_id = "'.$_SESSION["order_id"].'"  
                     ';  
                     $result = mysqli_query($connect, $query);  
                     while($row = mysqli_fetch_array($result))  
                     {  
                          $customer_details = '  
                          <label>'.$row["CustomerName"].'</label>  
                          <p>'.$row["Address"].'</p>  
                          <p>'.$row["City"].', '.$row["PostalCode"].'</p>  
                          <p>'.$row["Country"].'</p>  
                          ';  
                          $order_details .= "  
                               <tr>  
                                    <td>".$row["product_name"]."</td>  
                                    <td>".$row["product_quantity"]."</td>  
                                    <td>".$row["product_price"]."</td>  
                                    <td>".number_format($row["product_quantity"] * $row["product_price"], 2)."</td>  
                               </tr>  
                          ";  
                          $total = $total + ($row["product_quantity"] * $row["product_price"]);  
                     }  
                     echo '  
                     <h3 align="center">Order Summary for Order No.'.$_SESSION["order_id"].'</h3>  
                     <div class="table-responsive">  
                          <table class="table">  
                               <tr>  
                                    <td><label>Customer Details</label></td>  
                               </tr>  
                               <tr>  
                                    <td>'.$customer_details.'</td>  
                               </tr>  
                               <tr>  
                                    <td><label>Order Details</label></td>  
                               </tr>  
                               <tr>  
                                    <td>  
                                         <table class="table table-bordered">  
                                              <tr>  
                                                   <th width="50%">Product Name</th>  
                                                   <th width="15%">Quantity</th>  
                                                   <th width="15%">Price</th>  
                                                   <th width="20%">Total</th>  
                                              </tr>  
                                              '.$order_details.'  
                                              <tr>  
                                                   <td colspan="3" align="right"><label>Total</label></td>  
                                                   <td>'.number_format($total, 2).'</td>  
                                              </tr>  
                                         </table>  
                                    </td>  
                               </tr>  
                          </table>  
                     </div>  
                     ';  
                }  
                ?>  
           </div>  
      </body>  
 </html> 


Database rows are product_id’ ,‘product_name’ ,‘product_price’ , 'product_quantity I attached an preview of the project.Thank you very much,hope you’ll find a solution for me i’m out of ideas,and i can’t figure out.

This is one of those examples of making an end user page without laying out the groundwork first.

On something like this I would ask myself is there going to be more than one department, e.g. Electronics, Lighting, Clothing etc?

I would create a database table for departments adding known possibilities to get things started.

Then ask are there categories in this department, e.g. TV’s, Computers, Software etc?

I then create a database table for categories that has field named department to hold for example Electronics as the department and Computers as the category. I again add known possibilities to get things started.

Now depending on the products you are selling you might have other subcategories but for example you mentioned Brand.

I would make a table named Brands that has fields and holds (guess what)… the department and category and the brand.

Once you have these kinds of tables in place you can then make a backend interface to add products.
As you see there are three tables that can be selected from when entering product information by selecting Department, Category and Brand and entering other product details. All these fields should be added to your products table. One nice thing about doing this FIRST is that the terms used for Department, Category and Brand will always be the same in that Computers will always be Computers and not computer,PC,laptop etc or something else manually entered. This makes getting expected search results possible.

Having these tables in place and filled with product data allows you to then build a filter array built off the results of these tables.

<?php
$filter_array=array();
$allowed_dept=array();
$allowed_cats=array();
$allowed_brands=array();
$sql_menu = "SELECT
      d.department
    , c.category
    , b.brand
    FROM tbl_departments d
        LEFT JOIN tbl_categories c
            ON c.department = d.department
        LEFT JOIN tbl_brands b
            ON b.category = c.category AND b.department = d.department
    ORDER BY d.department,c.category,b.brand ASC";
$res_menu = mysqli_query($connect, $sql_menu); 
while($row_menu = mysqli_fetch_array($res_menu)) 
{       
    //Build filter_array
    $filter_array[$row_menu['department']][$row_menu['category']][$row_menu['brand']] = [$row_menu['brand']];
    //You can also define allowed search values for product query
    $allowed_dept[]   = $row_menu['department'];
    $allowed_cats[]   = $row_menu['category'];
    $allowed_brands[] = $row_menu['brand'];
}

//Set variables to allowed search variables
$search_department = (!empty($_POST['department']) && in_array($_POST['department'],$allowed_dept) ? $_POST['department'] : '');
$search_category  = (!empty($_POST['category']) && in_array($_POST['category'],$allowed_cats) ? $_POST['category'] : '');
$search_brand  = (!empty($_POST['brand']) && in_array($_POST['brand'],$allowed_brands) ? $_POST['brand'] : '');
?>

You will notice I also make ALLOWED arrays for each of these three filter types so when we POST selection values we can make sure they are allowed values and set them to SEARCH variables.

Then it’s just a matter of checking if the filter array is built, doing some checks for those SEARCH variables and using FOREACH to loop our selection options.

Adding a small form just below your tabs might work. Here’s a sample.

<div class="col-md-12" style="margin-top:12px;clear:both;">
    <form action="product.php" method="post">
        <select name="department" onchange="this.form.submit()">
            <option value=''></option>
            <?php
            if(!empty($filter_array)):
                foreach($filter_array as $dep => $ar):
                    $selected_department = ($search_department == $dep ? ' selected="selected"' :'');   
                    echo '<option value="'.$dep.'"'.$selected_department.'>'.$dep.'</option>'."\r";
                endforeach;
            endif;
            ?>
        </select>
       
        <select name="category" onchange="this.form.submit()">
            <option value=''></option>
            <?php
            if(!empty($filter_array) && array_key_exists($search_department,$filter_array)):
                foreach($filter_array[$search_department] as $cat => $ar2):
                    $selected_category = ($search_category == $cat ? ' selected="selected"' :'');   
                    echo '<option value="'.$cat.'"'.$selected_category.'>'.$cat.'</option>'."\r";
                endforeach;
            endif;
            ?>
        </select>
       
        <select name="brand" onchange="this.form.submit()">
            <option value=''></option>
            <?php
            if(!empty($filter_array) && array_key_exists($search_department,$filter_array) && array_key_exists($search_category,$filter_array[$search_department])):
                foreach($filter_array[$search_department][$search_category] as $brand => $ar):
                    $selected_brand = ($search_brand == $brand ? ' selected="selected"' :'');   
                    echo '<option value="'.$brand.'"'.$selected_brand.'>'.$brand.'</option>'."\r";
                endforeach;
            endif;
            ?>
        </select>
    </form>
</div>

Using these same SEARCH variables you can build a search conditions array to be used in your product query.

//Build search conditions array
$search_conditions=array();             
if(!empty($search_department)):
    $search_conditions[] = "department = '$search_department'";
endif;
if(!empty($search_category)):
    $search_conditions[] = "category = '$search_category'";
endif;
if(!empty($search_brand)):
    $search_conditions[] = "brand = '$search_brand'";
endif;

Then in the query just check for this array and implode it.

$query = "SELECT * FROM tbl_product ";   

if(!empty($search_conditions)):
    $query .= "WHERE ";
    $query .= implode(" AND ",$search_conditions);   
endif;  

$query .= " ORDER BY id ASC";

Anyway this might give you some ideas to get started.

Image of search form and echoing query.

2 Likes

Yea,you got my idea,and it will pop up my products?Also any ideas of left checkboxes filtering.Also can you give me the full source code,just if you want.I appreciated all your ideas,i’ll test them after work tommorow.Thank you!

Something like this,for lateral checkbox filter,thank you in advance.

Didn’t worked for me,prodcuts won’t show,on each product a got an field image,it is necesarly to build a new php file,or i can modify the product.php.Pls give me the full source code that you tested,and let me know if you have any other ideas about checkbox filters, i would appreciated.Thank you very much !

It is probably a matter of not having same Database tables or something along those lines. I noticed in your OP that mentioned product_name, product_price but your code example just uses name and price… Could be something like that.

I have some files I played with a bit last night. I added a new sub_categories table to use as a primary third dropdown option instead of brand. This gives the site a bit more flexibility. I also added a label field to the department and category tables so when you select a department or category different labels are shown for the sibling.

Much like before with product display, I query table and build sub-filter arrays based on current product fields we have, brand, size, color and price. This array is then turned into checkbox filters and shown if there are more than one option.
Price ranges are based on max and min price of query results of price.


Checked filters are then passed to primary query for product display.
Hey it’s one of those things you tweak, find and fix errors until you get it the way you want.
I will see about sending the page and sql files through PM.

1 Like

Thank you very much sir.I will see what i can do.I will wait for you pm with page and sql,thx alot for the time lost with me.Very very much appreciated.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.