PHP CRUD Scripts

PHP CRUD code: a simple application script to create, read, update and delete records.

PHP Simple CRUD Application Script

CRUD means the four basic things that you do with data in a database: Create, Read, Update and Delete. Almost every web application does some CRUD. Once you learn it with a users table, you can use the same idea for products, students or orders.

This is a small CRUD application in PHP and MySQL. It has only the files that are needed, so it is easy to understand, and it follows the basic security rules: prepared statements for all queries, escaped output and a CSRF token for forms and delete.


Files of the script

FilePurpose
database.sqlCreates the database and the users table
config.phpDatabase connection and small helper functions
index.phpRead: shows the list of users
add.phpCreate: form to add a new user
edit.phpUpdate: form to change a user
delete.phpDelete: removes a user

Put all files in one folder inside your local server (for example htdocs/crud in XAMPP) and open http://localhost/crud/. You should know the basics from the PHP MySQL tutorial and prepared statements.


1) database.sql

CREATE DATABASE IF NOT EXISTS crud_db
    CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

USE crud_db;

CREATE TABLE IF NOT EXISTS users (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL,
    mobile VARCHAR(15) NOT NULL
);

2) config.php

The file connects to the database and has three helpers: e() escapes text for HTML, csrf_token() creates the form token and csrf_check() checks it.

<?php
session_start();

// Database errors become exceptions (do not show them on a live site)
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$mysqli = new mysqli("localhost", "root", "", "crud_db");
$mysqli->set_charset("utf8mb4");

// Escape a value before printing it in HTML
function e($value): string
{
    return htmlspecialchars((string) $value, ENT_QUOTES, "UTF-8");
}

// CSRF token for forms
function csrf_token(): string
{
    if (empty($_SESSION["csrf"])) {
        $_SESSION["csrf"] = bin2hex(random_bytes(32));
    }
    return $_SESSION["csrf"];
}

function csrf_check(): void
{
    if (!hash_equals($_SESSION["csrf"] ?? "", $_POST["csrf"] ?? "")) {
        http_response_code(403);
        exit("Invalid request.");
    }
}

3) index.php (Read)

<?php
require_once "config.php";

$result = $mysqli->query("SELECT id, name, mobile, email FROM users ORDER BY id DESC");
?>
<h2>Users</h2>
<p><a href="add.php">Add New User</a></p>

<table border="1" cellpadding="6">
    <tr>
        <th>Name</th><th>Mobile</th><th>Email</th><th>Action</th>
    </tr>
    <?php while ($user = $result->fetch_assoc()) { ?>
    <tr>
        <td><?php echo e($user["name"]); ?></td>
        <td><?php echo e($user["mobile"]); ?></td>
        <td><?php echo e($user["email"]); ?></td>
        <td>
            <a href="edit.php?id=<?php echo (int) $user["id"]; ?>">Edit</a>
            <form method="post" action="delete.php" style="display:inline"
                  onsubmit="return confirm('Delete this user?');">
                <input type="hidden" name="csrf" value="<?php echo csrf_token(); ?>">
                <input type="hidden" name="id" value="<?php echo (int) $user["id"]; ?>">
                <button type="submit">Delete</button>
            </form>
        </td>
    </tr>
    <?php } ?>
</table>

There is no user input in this query, so a normal query is fine. Delete is a POST form with a token, not a link, so nobody can delete users by just opening a URL.

4) add.php (Create)

<?php
require_once "config.php";

$error = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    csrf_check();

    $name   = trim($_POST["name"] ?? "");
    $email  = filter_var(trim($_POST["email"] ?? ""), FILTER_VALIDATE_EMAIL);
    $mobile = trim($_POST["mobile"] ?? "");

    if ($name === "" || !$email || $mobile === "") {
        $error = "Please fill all fields with a valid email.";
    } else {
        $stmt = $mysqli->prepare("INSERT INTO users (name, email, mobile) VALUES (?, ?, ?)");
        $stmt->bind_param("sss", $name, $email, $mobile);
        $stmt->execute();

        header("Location: index.php");
        exit;
    }
}
?>
<h2>Add User</h2>
<p><a href="index.php">Go to Home</a></p>
<p style="color:red"><?php echo e($error); ?></p>

<form method="post">
    <input type="hidden" name="csrf" value="<?php echo csrf_token(); ?>">
    <p>Name: <input type="text" name="name" value="<?php echo e($_POST["name"] ?? ""); ?>"></p>
    <p>Email: <input type="text" name="email" value="<?php echo e($_POST["email"] ?? ""); ?>"></p>
    <p>Mobile: <input type="text" name="mobile" value="<?php echo e($_POST["mobile"] ?? ""); ?>"></p>
    <p><button type="submit">Add</button></p>
</form>

5) edit.php (Update)

<?php
require_once "config.php";

$id = (int) ($_GET["id"] ?? $_POST["id"] ?? 0);
$error = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    csrf_check();

    $name   = trim($_POST["name"] ?? "");
    $email  = filter_var(trim($_POST["email"] ?? ""), FILTER_VALIDATE_EMAIL);
    $mobile = trim($_POST["mobile"] ?? "");

    if ($name === "" || !$email || $mobile === "") {
        $error = "Please fill all fields with a valid email.";
    } else {
        $stmt = $mysqli->prepare("UPDATE users SET name = ?, email = ?, mobile = ? WHERE id = ?");
        $stmt->bind_param("sssi", $name, $email, $mobile, $id);
        $stmt->execute();

        header("Location: index.php");
        exit;
    }
}

// Get the current data of the user
$stmt = $mysqli->prepare("SELECT name, email, mobile FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if (!$user) {
    exit("User not found.");
}
?>
<h2>Edit User</h2>
<p><a href="index.php">Home</a></p>
<p style="color:red"><?php echo e($error); ?></p>

<form method="post">
    <input type="hidden" name="csrf" value="<?php echo csrf_token(); ?>">
    <input type="hidden" name="id" value="<?php echo $id; ?>">
    <p>Name: <input type="text" name="name" value="<?php echo e($user["name"]); ?>"></p>
    <p>Email: <input type="text" name="email" value="<?php echo e($user["email"]); ?>"></p>
    <p>Mobile: <input type="text" name="mobile" value="<?php echo e($user["mobile"]); ?>"></p>
    <p><button type="submit">Update</button></p>
</form>

6) delete.php (Delete)

<?php
require_once "config.php";

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    exit("Invalid request.");
}

csrf_check();

$id = (int) ($_POST["id"] ?? 0);

$stmt = $mysqli->prepare("DELETE FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();

header("Location: index.php");
exit;

What makes this version safe

Problem in simple scriptsWhat we did
SQL injection (values pasted in the query)Prepared statements with bind_param() for every query that uses a value
XSS (printing user text as it is)e() (htmlspecialchars) on every printed value
Delete or change with a simple linkPOST forms with a CSRF token, and csrf_check()
Wrong or empty dataValidation with trim(), filter_var() and checks
Database errors shown to visitorsErrors are thrown as exceptions, not printed
Note: Anyone can open this app, because it has no login. For a real project, protect these pages with a login (see the login and registration script), and show only the data that the user is allowed to see.

Related chapters: SELECT, INSERT, UPDATE and DELETE.