← Tous les articles

PHP and PDO: prepared statements for LIKE, IN() and ORDER BY

Everyone knows to use prepared statements. The SQL injections we find in code audits nearly always sit where developers were not sure how: a LIKE search, a list of IDs, or a user-selected sort column.

PHP and PDO: prepared statements for LIKE, IN() and ORDER BY

Key points

  • Configure PDO once: exceptions, a default fetch mode and real server-side prepares.
  • For IN(), generate one placeholder per value; for LIKE, escape % and _.
  • Column names and sort directions cannot be bound, so pick them from a whitelist.

In the PHP code audits we run, SQL injection is almost never in the login query; everyone has learned to protect that one. It hides in the catalogue search, the multi-category filter or the sortable admin table, the places where a developer could not work out how to use a placeholder and fell back to string concatenation. Here is a clean way to handle those three cases with PDO.

A properly configured connection

Three options make a real difference. Exceptions stop queries from failing silently. Turning off emulation means MySQL prepares the statement itself and parameter types are preserved.

$pdo = new PDO($dsn, $user, $password, [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false, // real server-side prepares
]);

That last option matters in practice. With emulation on, passing a number to execute() for a LIMIT yields LIMIT '20', which MySQL rejects. That error message is often what pushes people to concatenate “just for pagination”.

Searching with LIKE

A placeholder blocks injection, but not wildcards. A user who types % matches the whole table, and _ matches any single character. Escape them before adding your own.

// Search: escape LIKE wildcards before adding your own
$term = addcslashes($_GET['q'] ?? '', '%_\');

$stmt = $pdo->prepare('SELECT id, name FROM products WHERE name LIKE :q LIMIT 50');
$stmt->execute(['q' => '%' . $term . '%']);
$products = $stmt->fetchAll();

Keep a LIMIT on these queries. A leading-wildcard search cannot use a regular index, and on a large table that cost adds up quickly with search-as-you-type.

A list of values in IN()

One placeholder cannot take an array. Build the placeholder list from the number of values, never from the values themselves.

function find_products(PDO $pdo, array $ids): array
{
    $ids = array_values(array_unique(array_map('intval', $ids)));
    if ($ids === []) {
        return []; // "IN ()" is a syntax error
    }

    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $stmt = $pdo->prepare("SELECT id, name, price FROM products WHERE id IN ($placeholders)");
    $stmt->execute($ids);

    return $stmt->fetchAll();
}

The empty array is what breaks in production: a filter with no box ticked produces IN (), a syntax error. The early return handles it.

User-selected sorting

Column names and keywords such as ASC cannot be bound. The only safe approach is a lookup table: the user sends a key, your code picks the column.

// Column names cannot be bound: map user input to a whitelist
$sortable = ['name' => 'name', 'price' => 'price', 'date' => 'created_at'];
$column = $sortable[$_GET['sort'] ?? ''] ?? 'created_at';
$direction = ($_GET['dir'] ?? '') === 'asc' ? 'ASC' : 'DESC';

$page = max(1, (int) ($_GET['page'] ?? 1));

$stmt = $pdo->prepare("SELECT id, name, price FROM products
                       ORDER BY $column $direction LIMIT :limit OFFSET :offset");
$stmt->bindValue('limit', 20, PDO::PARAM_INT);
$stmt->bindValue('offset', ($page - 1) * 20, PDO::PARAM_INT);
$stmt->execute();

The incoming value never reaches the SQL; only strings written in your code do. Apply that rule to any dynamic part of a query that is not a plain value.

FAQ

Isn’t intval() enough for IDs?

It does prevent injection on that field, but combine both: cast for business rules, bind for security. If an ID ever becomes a string, the placeholder still protects you.

What about WordPress?

Same principle with $wpdb->prepare() and its %d and %s placeholders. For LIKE, WordPress provides $wpdb->esc_like().

Not sure whether your PHP application is exposed? We run code and security audits and fix what we find without rewriting the whole project.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →