A safe search form with PHP and LIKE

Intermediate  Nov 3, 2026

Search a table by keyword without SQL injection.

A safe search form with PHP and LIKE
The steps of this tutorial at a glance.
The steps of this tutorial at a glance.

The form

<form method="get">
  <input type="search" name="q" placeholder="Search...">
  <button>Search</button>
</form>
How the code in this section fits into the page.
How the code in this section fits into the page.

The query

<?php
require __DIR__ . '/db.php';

$q = trim((string)($_GET['q'] ?? ''));
$rows = [];

if ($q !== '') {
    // escape the LIKE wildcards typed by the user
    $safe = addcslashes($q, '%_\\');
    $stmt = $pdo->prepare('SELECT id, title FROM articles WHERE title LIKE ? OR body LIKE ? LIMIT 20');
    $stmt->execute(['%' . $safe . '%', '%' . $safe . '%']);
    $rows = $stmt->fetchAll();
}

foreach ($rows as $r) {
    echo '<p>', htmlspecialchars($r['title']), '</p>';
}
How the code in this section fits into the page.
How the code in this section fits into the page.

Key points

  • The value is passed as a parameter, never joined into the SQL text.
  • % and _ are wildcards inside LIKE. Escaping them stops a user from searching for "everything".
  • Print results with htmlspecialchars().
  • Put a LIMIT on it so one search cannot return the whole table.
The main points of this section.
The main points of this section.

Limits of LIKE

LIKE '%word%' cannot use a normal index and is slow on big tables. For large data use a FULLTEXT index (see the advanced tutorial on MySQL full-text search).

More tutorials