Editorial illustration of documents being indexed and searched through a database using highlighted matching terms.

Not every web application needs Elasticsearch, OpenSearch, or a dedicated search infrastructure. For many projects, the immediate requirement is much simpler: allow users to search articles, documentation, product descriptions, or internal records and receive reasonably relevant results.

PHP developers can implement this functionality using SQLite’s FTS5 extension, a full-text search engine integrated directly into SQLite.

FTS5 supports tokenized text indexing, phrase searches, relevance ranking, and contextual snippets. Combined with PHP’s PDO SQLite driver, it provides a practical search solution without introducing a separate search server.

Let’s build a small article search engine and examine where this approach works well, where it becomes limiting, and which implementation details matter in production.

Why SQL LIKE Is Not a Search Engine

A common first implementation of search uses a SQL LIKE expression:

SELECT *
FROM articles
WHERE title LIKE '%database%'
   OR body LIKE '%database%';

This can be sufficient for small datasets, but it does not provide the capabilities users normally expect from full-text search.

It does not inherently rank documents according to relevance, recognize phrases as indexed search terms, or generate contextual excerpts showing why a document matched.

Leading-wildcard patterns can also prevent ordinary B-tree indexes from efficiently narrowing the search.

FTS5 addresses these problems using an inverted index: instead of repeatedly scanning every document for a substring, SQLite maintains a searchable structure associating indexed terms with documents.

Step 1: Check Your PHP Environment

Our implementation requires PHP 8.2 or later, the PDO SQLite driver, and a SQLite library compiled with FTS5 support.

FTS5 is commonly available in modern SQLite builds, but its presence should be verified rather than assumed.

<?php

declare(strict_types=1);

if (!extension_loaded('pdo_sqlite')) {
    throw new RuntimeException(
        'PDO SQLite is required.'
    );
}

$db = new PDO('sqlite::memory:');

$db->setAttribute(
    PDO::ATTR_ERRMODE,
    PDO::ERRMODE_EXCEPTION
);

try {
    $db->exec(
        'CREATE VIRTUAL TABLE fts_check USING fts5(text)'
    );

    echo "FTS5 is available." . PHP_EOL;
} catch (PDOException $exception) {
    throw new RuntimeException(
        'SQLite FTS5 is unavailable.',
        previous: $exception
    );
}

If the test succeeds, we can proceed with an indexed article collection.

Step 2: Create a Searchable Article Index

For this tutorial, we will use a standalone FTS5 table containing article titles and body text. This keeps the example compact and makes it easy to understand the indexing process.

In a larger application, the search index may instead be synchronized with a separate canonical articles table.

CREATE VIRTUAL TABLE articles USING fts5(
    title,
    body,
    tokenize = 'unicode61'
);

The unicode61 tokenizer handles Unicode text using SQLite’s tokenization rules. It is useful for many ordinary text-search requirements, although it does not provide full linguistic stemming or sophisticated language-specific analysis.

FTS5 also supports other tokenizer configurations, including porter for English stemming and trigram for substring-oriented searches.

Step 3: Index Documents and Search by Relevance

The following complete example creates an in-memory index, inserts four articles, and searches for documents containing the terms “php” and “database”.

Save it as search.php.

<?php

declare(strict_types=1);

if (!extension_loaded('pdo_sqlite')) {
    throw new RuntimeException(
        'Enable the pdo_sqlite extension.'
    );
}

$db = new PDO('sqlite::memory:', null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

$db->exec(
    "CREATE VIRTUAL TABLE articles USING fts5(
        title,
        body,
        tokenize = 'unicode61'
    )"
);

$documents = [
    [
        'PHP and SQLite Search',
        'Build a database search feature using PHP and SQLite FTS5.'
    ],
    [
        'PHP Database Connections',
        'Use PDO to connect PHP applications to a database.'
    ],
    [
        'Modern CSS Layouts',
        'Learn responsive layouts with CSS Grid and Flexbox.'
    ],
    [
        'SQLite Full-Text Indexing',
        'SQLite FTS5 provides efficient full-text indexing for applications.'
    ],
];

$insert = $db->prepare(
    'INSERT INTO articles (title, body) VALUES (?, ?)'
);

foreach ($documents as $document) {
    $insert->execute($document);
}

function searchArticles(
    PDO $db,
    string $input
): array {
    $terms = preg_split(
        '/\s+/u',
        trim($input),
        -1,
        PREG_SPLIT_NO_EMPTY
    );

    if ($terms === false || $terms === []) {
        return [];
    }

    if (count($terms) > 8) {
        throw new InvalidArgumentException(
            'Too many search terms.'
        );
    }

    $phrases = [];

    foreach ($terms as $term) {
        if (
            !preg_match('/^[\p{L}\p{N}]+$/u', $term)
        ) {
            throw new InvalidArgumentException(
                'Use letters and numbers only.'
            );
        }

        $phrases[] = '"' . $term . '"';
    }

    $query = implode(' AND ', $phrases);

    $statement = $db->prepare(
        "SELECT
            rowid,
            title,
            snippet(
                articles,
                1,
                '[',
                ']',
                '...',
                12
            ) AS excerpt,
            bm25(articles, 5.0, 1.0) AS score
         FROM articles
         WHERE articles MATCH :query
         ORDER BY score ASC
         LIMIT 10"
    );

    $statement->execute([
        'query' => $query,
    ]);

    return $statement->fetchAll();
}

$results = searchArticles(
    $db,
    'php database'
);

foreach ($results as $result) {
    echo $result['title'] . PHP_EOL;
    echo $result['excerpt'] . PHP_EOL;
    echo 'Score: ' . $result['score'] . PHP_EOL;
    echo PHP_EOL;
}

Run the example using:

php search.php

The search should return the two articles containing both terms: “PHP and SQLite Search” and “PHP Database Connections”. Their order is determined by the BM25 relevance calculation.

The exact numeric scores depend on the indexed collection. They should not be treated as percentages or compared directly across unrelated indexes.

Step 4: Understand BM25 Ranking

FTS5 provides the bm25() function for ranking matching documents.

BM25 considers factors including term frequency, document length, and how commonly terms appear across the indexed collection.

SQLite’s implementation returns numerically lower scores for better matches, which is why the example sorts in ascending order.

The additional arguments assign weights to indexed columns:

bm25(articles, 5.0, 1.0)

Here, matches in the title receive five times the weight of matches in the body.

This is a useful editorial-search rule: an article whose title directly addresses the search topic may deserve greater prominence than an article mentioning the same terms only in passing.

These weights are design choices, not universal relevance constants. Applications should evaluate them against representative search queries.

Step 5: Generate Search Snippets

Search results are more useful when they show the context in which a term appears.

FTS5 provides snippet() to extract a relevant fragment from a matching document.

snippet(
    articles,
    1,
    '[',
    ']',
    '...',
    12
)

The first numeric argument selects the body column, whose index is 1. The next arguments specify the markers surrounding matches, the truncation indicator, and the maximum snippet length in tokens.

For example, a result might contain a fragment similar to:

Build a [database] search feature using [PHP] and SQLite FTS5.

The example deliberately uses plain-text brackets rather than HTML tags.

When presenting search results on a website, developers must escape document content before rendering it. Directly inserting snippets containing untrusted HTML into a page can create cross-site scripting vulnerabilities.

What About Search Query Injection?

Prepared statements protect SQL values from being interpreted as SQL syntax, but FTS5 has its own query language.

Operators such as AND, OR, NOT, and NEAR have special meanings inside an FTS5 MATCH expression.

Therefore, passing arbitrary user input as a bound MATCH value avoids SQL injection but does not automatically make the input a literal full-text query.

Our example intentionally accepts only letters and numbers, places each term inside double quotes, and joins the terms using AND.

This provides predictable behavior for a simple keyword-search interface. It is deliberately restrictive: punctuation, hyphenated words, and advanced search operators are not supported.

Applications requiring richer search syntax should implement a dedicated parser and validate supported operators rather than directly exposing the full FTS5 query language to users.

Moving Beyond the In-Memory Example

Our example uses sqlite::memory: so the database disappears when the process terminates.

A persistent application can use a file-backed database instead:

$db = new PDO(
    'sqlite:' . __DIR__ . '/search.sqlite'
);

Production applications should also consider how the search index stays synchronized with the primary article records.

If articles are stored in a separate table, FTS5 supports external-content tables and triggers that maintain the index when documents are inserted, updated, or deleted.

Another option is to update the index through application-level transactions whenever the underlying content changes.

The important requirement is consistency: stale search indexes can display outdated or deleted information.

When SQLite FTS5 Is the Right Choice

SQLite FTS5 is attractive for embedded applications, documentation sites, editorial archives, internal tools, and modest search workloads where introducing a separate search service would add unnecessary operational complexity.

It also offers a useful development environment for experimenting with tokenization, indexing, and relevance ranking before selecting a larger search architecture.

However, FTS5 is not a universal replacement for dedicated search platforms.

Applications requiring distributed indexing, extensive language-specific analysis, sophisticated faceting, large-scale horizontal scaling, or specialized ranking pipelines may benefit from a dedicated search system.

SQLite’s concurrency model also matters. Multiple readers are supported, but write operations are serialized, which may become significant in systems with frequent concurrent index updates.

Choosing between SQLite and a dedicated search platform should therefore depend on measured requirements rather than assumptions about which technology is more sophisticated.

A Small Search Engine with Useful Capabilities

With a virtual table, a prepared query, and a small amount of PHP, we have created a searchable article index supporting keyword matching, relevance ranking, and contextual excerpts.

The implementation is intentionally simple, but the underlying concepts are the same ones encountered in larger search systems: tokenization, inverted indexes, ranking, and query interpretation.

For PHP applications that need practical full-text search without an additional service, SQLite FTS5 deserves serious consideration. The best architecture is not always the one with the most components; it is the one that meets the application’s requirements with manageable complexity.

LEAVE A REPLY

Please enter your comment!
Please enter your name here