Show all products when search is blank (Opencart 2.3.x)

Objectives of the blog

After reading this blog you will be able to display all products when the search is blank.

Problem Statement

Currently in Opencart, when user search for any string using search functionality, then no products are returned if no search product found in database. We want to make it return all the products when search is empty.

Code Implementation

To achieve this, we will have to make some changes in the model function which we are using to fetch products from database on the basis of entered search keyword.

Here we are making changes in getProducts()  function of model catalog/model/catalog/product.php as we are using this function to display results on the basis of search keyword.

Note: you can make same changes in the model function which you are using to fetch products.

Here is the code which we have added in the model:

/*Checked if the result empty (affected rows 0) of query which is running to fetch data on the basis of search keyword.
* If yes then added new query to fetch new added products and executed same.  
* By doing this we will display our new products on the search page instead of showing blank page.
*/
if($query->num_rows == 0){
   $sql = "SELECT DISTINCT p.product_id  
           FROM " . DB_PREFIX . "product p  
           LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id)  
           LEFT JOIN " . DB_PREFIX . "product_to_store p2s ON (p.product_id = p2s.product_id)  
           WHERE p.status = '1' AND p.date_available <= NOW() AND p2s.store_id = '" . (int)$this->config->get('config_store_id') . "'  
           GROUP BY p.product_id ORDER BY p.product_id DESC LIMIT 20";
   $query = $this->db->query($sql);
}

Add this code just after executing main query or just after line ($query = $this->db->query($sql)).

In this code first we have checked the number of affected row by the main query (used to fetch data on the basis of search keyword). If the affected row is 0 ($query->num_rows == 0) then added our query to fetch new added products.

By doing this we will display our new products on the search page instead of showing blank page.

Note: here we have written query to fetch new added products from the database if search is empty. You can also add query to fetch special or best seller products according to your requirement.

Summary

After making the following changes in the model file, new added products will be shown when the search is empty.

Shivika Tomar

Shivika Tomar

Shivika Tomar is a passionate PHP developer. Her area of interest is website development. She loves to bring healing to stressful and sad peoples.

Leave a Reply

Your email address will not be published. Required fields are marked *