Smarter Search and Recommendations for PHP E-commerce Sites

How to make product search forgive typos and understand synonyms, and how to add "customers also bought" and similar-product suggestions to a PHP store, starting with plain SQL.

On many small and mid-sized online stores, the search box is the weakest part of the site. A shopper types "bluetooth earfone" or "kurta for men cotton", gets "No products found", and leaves, even though the store stocks exactly what they wanted. Product pages have the same problem in a different form: they show a single item and offer no sensible next step.

Improving search and recommendations does not require a data science team. Most PHP stores, whether built on WooCommerce, Magento, Laravel or custom code, can make meaningful progress in stages: fix the basic search, add typo tolerance and synonyms, then add recommendations based on what customers actually buy. This article walks through those stages in order of effort.

Start by measuring what people search for

Before changing anything, log every search: the query, the number of results, and whether the shopper clicked a result or added something to the cart. A simple table with those columns is enough. After a few weeks, two lists tell you most of what you need:

  • Zero-result queries, which reveal misspellings, regional terms and products you do not stock.
  • Searches with results but no clicks, which suggest poor ranking.

Indian stores often see mixed-language queries, transliterated Hindi or regional words, and brand names spelled several ways. Your logs will show which ones matter for your catalogue.

Typo-tolerant search

A LIKE '%term%' query, which many stores start with, cannot use a normal index, is slow on large tables and matches only exact substrings. MySQL's FULLTEXT indexes improve relevance and speed but still do not correct spelling.

For a catalogue of a few hundred products, you can add a "did you mean" step in PHP: when a search returns nothing, compare each query word against a list of known product words using levenshtein() and retry with the closest match within a small distance. This is cheap to build but does not scale to large catalogues.

Beyond that, use a dedicated search engine. Open-source options such as Meilisearch, Typesense and OpenSearch provide typo tolerance, prefix matching ("search as you type"), filters and facets out of the box, and have PHP clients. Laravel Scout integrates with several of them. The usual architecture is:

  1. The database remains the source of truth for products, prices and stock.
  2. A background job pushes product changes to the search index.
  3. The search page queries the engine, then fetches live price and stock from the database or cache.

Synonyms and language

Typo tolerance will not connect "mobile" with "smartphone" or "chappal" with "slippers". That needs a synonym list, which search engines let you configure. Build it from your zero-result log rather than guessing, and keep it in version control. Typical entries for an Indian store include English and Hindi equivalents, British and American spellings ("colour" and "color"), common abbreviations ("tv", "television") and units ("1 kg", "1000 g").

Also decide which fields matter most. A match in the product title should usually rank above a match in the long description, and in-stock items above out-of-stock ones. Most engines let you set these ranking rules explicitly.

"Customers also bought" with plain SQL

The simplest useful recommendation is co-purchase: products that appear in the same orders as the one being viewed. If you have order history, you can compute this with one query. The example below is for MySQL or MariaDB and assumes typical orders and order_items tables.

SELECT oi2.product_id,
       COUNT(DISTINCT oi2.order_id) AS times_bought_together
FROM order_items AS oi1
JOIN order_items AS oi2
  ON oi2.order_id = oi1.order_id
 AND oi2.product_id <> oi1.product_id
JOIN orders AS o
  ON o.id = oi1.order_id
JOIN products AS p
  ON p.id = oi2.product_id
WHERE oi1.product_id = ?
  AND o.status = 'completed'
  AND o.created_at >= NOW() - INTERVAL 180 DAY
  AND p.is_active = 1
  AND p.stock_qty > 0
GROUP BY oi2.product_id
HAVING times_bought_together >= 3
ORDER BY times_bought_together DESC
LIMIT 6;

A few practical points:

  • Bind the product ID with a prepared statement in PDO; never concatenate it into the SQL.
  • The HAVING threshold avoids recommending pairs that happened together once by chance. Tune it to your order volume.
  • Very popular items, such as a carry bag or gift wrap, will appear with everything. Exclude them, or divide the co-purchase count by each product's overall popularity.
  • Do not run this on every page view. Compute it nightly with a cron job into a product_recommendations table, and read from that table on the product page.
  • For new products with no orders, fall back to bestsellers in the same category.

Similar products with embeddings

Co-purchase data answers "what goes with this?". Shoppers also want "what is like this?", for example other cotton kurtas in a similar style and price. Category and attribute filters handle part of this. Embeddings handle the fuzzier part.

An embedding model converts text (and, with some models, images) into a list of numbers so that similar items end up close together. You generate an embedding for each product from its title, key attributes and description, store it, and find nearest neighbours using cosine similarity. Many search engines, as well as PostgreSQL with the pgvector extension, can store vectors and perform this search for you. For a small catalogue you can even precompute neighbours in PHP:

function cosineSimilarity(array $a, array $b): float
{
    $dot = $normA = $normB = 0.0;
    foreach ($a as $i => $value) {
        $dot   += $value * $b[$i];
        $normA += $value ** 2;
        $normB += $b[$i] ** 2;
    }
    return $dot / (sqrt($normA) * sqrt($normB) ?: 1.0);
}

Run this comparison offline for every product pair in a category, keep the top few matches, and store them just like the co-purchase results. Embeddings can also power "semantic" search, where a query like "gift for a tea lover" finds tea sets and kettles that do not contain those exact words; most teams combine this with keyword search rather than replacing it.

Measure the results

Track clicks and add-to-cart events on each recommendation block and on search results, and compare against the period before the change. Keep a simple fallback in place so the page never shows an empty block, and review zero-result queries every month. Small, steady improvements based on real data tend to beat a large one-off project.

How NextWebGen can help

NextWebGen builds and maintains PHP e-commerce stores, including search engine integration, synonym and ranking setup, and recommendation features based on your own order data. If your store's search is losing sales, have a look at our e-commerce development services.