Skip to main content

Lesson 2 of 7

Prepared Statements - CRUD with Named Parameters

Prepared statements separate SQL structure from data - the database engine receives them separately, making SQL injection structurally impossible. Named parameters (:name) make queries readable and parameter-order-independent. Every database query in production PHP MUST use prepared statements.

16 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Full CRUD with Prepared Statements

Full CRUD with Prepared Statements
<?php
declare(strict_types=1);

class PostRepository {
    public function __construct(private readonly PDO $pdo) {}

    // ── CREATE ────────────────────────────────────────────────
    public function create(array $data): int {
        $sql = "
            INSERT INTO posts (title, slug, body, author_id, status, created_at)
            VALUES (:title, :slug, :body, :author_id, :status, UTC_TIMESTAMP())
        ";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([
            ":title"     => $data["title"],
            ":slug"      => $data["slug"],
            ":body"      => $data["body"],
            ":author_id" => $data["author_id"],
            ":status"    => $data["status"] ?? "draft",
        ]);
        return (int) $this->pdo->lastInsertId();
    }

    // ── READ - single ─────────────────────────────────────────
    public function findById(int $id): ?array {
        $stmt = $this->pdo->prepare(
            "SELECT p.*, u.name AS author_name
             FROM posts p
             JOIN users u ON u.id = p.author_id
             WHERE p.id = :id
             LIMIT 1"
        );
        $stmt->execute([":id" => $id]);
        $row = $stmt->fetch();   // PDO::FETCH_ASSOC set globally
        return $row !== false ? $row : null;
    }

    // ── READ - list with pagination ───────────────────────────
    public function findPublished(int $limit = 10, int $offset = 0): array {
        $stmt = $this->pdo->prepare(
            "SELECT p.id, p.title, p.slug, p.status, p.created_at, u.name AS author_name
             FROM posts p
             JOIN users u ON u.id = p.author_id
             WHERE p.status = 'published'
             ORDER BY p.published_at DESC
             LIMIT :limit OFFSET :offset"
        );
        // bindValue needed for LIMIT/OFFSET - must be cast to int
        $stmt->bindValue(":limit",  $limit,  PDO::PARAM_INT);
        $stmt->bindValue(":offset", $offset, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }

    // ── UPDATE ────────────────────────────────────────────────
    public function update(int $id, array $data): bool {
        $stmt = $this->pdo->prepare(
            "UPDATE posts
             SET    title = :title, body = :body, status = :status, updated_at = UTC_TIMESTAMP()
             WHERE  id = :id"
        );
        $stmt->execute([
            ":title"  => $data["title"],
            ":body"   => $data["body"],
            ":status" => $data["status"],
            ":id"     => $id,
        ]);
        return $stmt->rowCount() > 0;
    }

    // ── DELETE ────────────────────────────────────────────────
    public function delete(int $id): bool {
        $stmt = $this->pdo->prepare("DELETE FROM posts WHERE id = :id");
        $stmt->execute([":id" => $id]);
        return $stmt->rowCount() > 0;
    }

    // ── COUNT ─────────────────────────────────────────────────
    public function countPublished(): int {
        $stmt = $this->pdo->query("SELECT COUNT(*) FROM posts WHERE status = 'published'");
        return (int) $stmt->fetchColumn();
    }

    // ── SEARCH - LIKE query ───────────────────────────────────
    public function search(string $term, int $limit = 20): array {
        $likeTerm = "%" . $term . "%";   // wildcards added IN PHP, bound as value
        $stmt = $this->pdo->prepare(
            "SELECT id, title, slug FROM posts
             WHERE (title LIKE :term OR body LIKE :term) AND status = 'published'
             ORDER BY published_at DESC LIMIT :limit"
        );
        $stmt->bindValue(":term",  $likeTerm, PDO::PARAM_STR);
        $stmt->bindValue(":limit", $limit,    PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }
}

Quick Quiz

Tip

Tip

Practice Prepared Statements CRUD with Named Parameters in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Prepared Statements - CRUD with Named Parameters

Practice Task

Note

Practice Task - (1) Write a working example of Prepared Statements CRUD with Named Parameters from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Prepared Statements CRUD with Named Parameters is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/7 done