PHP 8 Intermediate PDO & Security · 8 min read

PHP PDO SELECT with a Prepared Statement

Lesson 18 of 43 in the PHP 8 learning path.

How do I SELECT a row by id without concatenating SQL?

A lesson id that arrives from a route is data, not SQL. Concatenating it into the query text is SQL injection (SQLi): the database parses whatever string you glued on. A prepared statement keeps the SQL fixed and sends the id as a bound value. The sample prepares SELECT id, title, track, seats FROM lessons WHERE id = :id, executes with ['id' => $id], and fetches one associative row. fetch() returns false when nothing matched. The method turns that into null so the caller can show "lesson not found" without a warning.

The connection uses the same options as the error-mode lesson: exceptions, associative fetches, native prepares, and utf8mb4. The runner inserts one classroom row so the SELECT has a target, then looks up id 0, which is not a real autoincrement value, and prints missing=none. The id in the lookup is an int passed to execute(). It is never interpolated into the SQL string.

Syntax & Parameters

Syntax
$statement = $pdo->prepare('SELECT id, title, track, seats FROM lessons WHERE id = :id');
$statement->execute(['id' => $id]);

Example

src/LessonRepository.php
<?php

declare(strict_types=1);

function gradebook(): PDO
{
    $password = getenv('GRADEBOOK_PASSWORD');
    if ($password === false) {
        throw new RuntimeException('Set GRADEBOOK_PASSWORD for the grade book database user.');
    }
    $host = getenv('GRADEBOOK_HOST') ?: '127.0.0.1';
    $database = getenv('GRADEBOOK_DATABASE') ?: 'gradebook';
    $user = getenv('GRADEBOOK_USER') ?: 'gradebook_app';
    return new PDO("mysql:host={$host};dbname={$database};charset=utf8mb4", $user, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);
}
final class LessonRepository
{
    public function __construct(private readonly PDO $pdo)
    {
    }

    public function find(int $id): ?array
    {
        $statement = $this->pdo->prepare(
            'SELECT id, title, track, seats FROM lessons WHERE id = :id'
        );
        $statement->execute(['id' => $id]);
        $row = $statement->fetch();

        return $row === false ? null : $row;
    }
}

try {
    $pdo = gradebook();
    $pdo->exec('CREATE TABLE IF NOT EXISTS lessons (id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, title VARCHAR(160) NOT NULL, track VARCHAR(40) NOT NULL, seats SMALLINT UNSIGNED NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci');
    $insert = $pdo->prepare('INSERT INTO lessons (title, track, seats) VALUES (:title, :track, :seats)');
    $insert->execute(['title' => 'Lab safety briefing', 'track' => 'web', 'seats' => 24]);
    $lessons = new LessonRepository($pdo);
    $found = $lessons->find((int) $pdo->lastInsertId());
    $missing = $lessons->find(0);
    echo 'found=' . ($found['title'] ?? 'none') . "\n";
    echo 'seats=' . ($found['seats'] ?? 'none') . "\n";
    echo 'missing=' . ($missing === null ? 'none' : $missing['title']) . "\n";
} catch (PDOException) {
    error_log('Lesson lookup failed.');
    echo "The lesson could not be loaded. Please try again shortly.\n";
} catch (RuntimeException $exception) {
    error_log($exception->getMessage());
    echo "The lesson could not be loaded. Please try again shortly.\n";
}

Expected Output

found=Lab safety briefing
seats=24
missing=none

Line-by-Line Walkthrough

  1. declare(strict_types=1) checks gradebook() and find() for calls in this file. find() requires an int id.
  2. gradebook() opens MySQL with utf8mb4, ERRMODE_EXCEPTION, FETCH_ASSOC, and native prepares.
  3. LessonRepository::find() prepares a SELECT whose only variable part is the parameter :id.
  4. execute(['id' => $id]) binds the integer. The id is not concatenated into the SQL string.
  5. fetch() returns the associative row or false. false becomes null so a missing lesson is an empty result.
  6. The runner creates the lessons table if needed and inserts Lab safety briefing so the SELECT has a row.
  7. find() is called with the new id from lastInsertId(), cast to int.
  8. A second find(0) represents an id that is not in the table. The method returns null.
  9. The echoes print found=Lab safety briefing, seats=24, and missing=none.
  10. PDOException is logged without getMessage() in the response. The visitor sees a generic sentence.

Common Pitfalls & Security

SQL injection (SQLi) is the bug this method closes. The database server parses the statement once and receives the id as data. String concatenation parses the id as SQL. A missing row is not an error. Treating false as an array causes a warning and a blank page. Showing the driver message to students leaks the query text, which makes the next injection attempt easier.

  • Unsafe anti-pattern (do not ship): "SELECT * FROM lessons WHERE id = $id" concatenates the id into the SQL text. Bind :id.
  • fetch() returns false when the row is absent. Reading $row["title"] on false warns. Convert false to null and branch.
  • SELECT * makes the PHP array depend on every new column. Name id, title, track, and seats.
  • A string id from the query string should be validated to an int before find(). The method signature already demands an int.
  • Emulated prepares can hide type issues. This connection sets ATTR_EMULATE_PREPARES to false.
  • Catching PDOException inside find() and returning null makes an outage look like a missing lesson. Let it throw to the boundary.

Best Practices & Modern Standards

On PHP 8.3, prepare the SELECT, bind the id, and fetch under ERRMODE_EXCEPTION. Keep the SQL in one literal so a reviewer can see there is no interpolation. Return null for an empty result and let connection or syntax failures throw.

Cast route parameters to int at the controller after you know they are numeric. Pass that int into the repository. Escape the title when you render HTML. The SELECT being safe does not make the title safe to drop into a page. Encoding and binding solve different problems.

Real-World Use

A teacher opens one lesson from the grade book. The route has already checked that the id belongs to their section, and find() loads Lab safety briefing with 24 seats. An old bookmark whose id is gone returns null, and the page says the lesson is not available. The id never becomes part of the SQL string, so a crafted route cannot change the query shape.

Frequently Asked Questions

Why is the id a parameter instead of part of the SQL?

The parameter keeps the id as data. Concatenating it lets the database parse it as SQL, which is SQL injection. execute(["id" => $id]) is the bind.

What does find() return when the row is missing?

null. fetch() returns false, and the method converts that to null. The sample prints missing=none for id 0.

Does a prepared statement encode HTML?

No. It protects the query. When you print title in HTML, run it through htmlspecialchars. The lesson title is still text.

Why does the runner insert a row?

So the file can be executed and the SELECT has a known lesson to find. The lookup itself is find(), which only binds :id. Production creates the table in a migration.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…