Skip to content

PHP Tutorial Database CRUD

CRUD Explained

Lesson 270 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Almost every web application is built on four operations. They have a name: CRUD.

LetterOperationSQLTypical page
CCreateINSERT“Add product” form
RReadSELECTProduct list and product page
UUpdateUPDATE“Edit product” form
DDeleteDELETEDelete button

A blog (posts), a shop (products), a task list (tasks), a contact manager: all are CRUD with different data.

CRUD and HTTP

OperationRequest
List / showGET /products, GET /products?id=3
Show the create formGET /product-new.php
CreatePOST /product-new.php
Show the edit formGET /product-edit.php?id=3
UpdatePOST /product-edit.php
DeletePOST /product-delete.php

Reading uses GET. Anything that changes data uses POST (see POST Method).

The plan for this chapter

We will build a small product manager, one operation at a time, and put it together in the last lesson.

The table (from Creating a Database and Table):

query.sql
SQL
CREATE TABLE products (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(150) NOT NULL,
    price DECIMAL(10,2) NOT NULL,
    stock INT NOT NULL DEFAULT 0,
    category VARCHAR(50) NOT NULL DEFAULT 'general'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

The files:

Text
PLAIN
product-manager/
├── db.php                 the PDO connection
├── ProductRepository.php  all SQL lives here
├── index.php              list, search, filter, sort, pagination
├── product-form.php       create and edit form
├── product-delete.php     deletes (POST only)
└── layout/header.php, footer.php

Why a repository?

Putting all SQL for products in one class (a repository) keeps your pages clean and your queries in one place. A page calls $repo->find(3) and does not care about SQL.

index.php
PHP
<?php
final class ProductRepository
{
    public function __construct(private PDO $pdo) {}

    public function find(int $id): ?array
    {
        $statement = $this->pdo->prepare("SELECT id, name, price, stock, category FROM products WHERE id = :id");
        $statement->execute(["id" => $id]);

        return $statement->fetch() ?: null;
    }
}

$repo = new ProductRepository(require __DIR__ . "/db.php");

echo $repo->find(1)["name"];
Output
OUTPUT
Notebook

The safety rules for every page

  1. Validate every input before it reaches the database.
  2. Use prepared statements for every value.
  3. Escape every value you print into HTML.
  4. Use POST for changes, and a CSRF token (see CSRF).
  5. Check that the user is allowed to do the operation.
  6. After a successful change, redirect (Post/Redirect/Get).
  7. Show friendly errors. Log the technical details.
info
Why this matters in Laravel
Laravel has “resource controllers” with exactly these seven routes (index, create, store, show, edit, update, destroy). Once you build CRUD by hand, you understand what the framework generates for you.