EthicsComputerCourses
Join training +91 90532 10052

CRUD with Prepared Statements

LAMP Stack · Lesson 6 of 20 Intermediate 12 min read Updated

By the end of this lesson ShikshaPortal will manage its students: list and search them, show one, add a new admission, correct a record, mark a student as left and delete a row added by mistake. Every query uses a prepared statement, every change uses a POST form, and database rules such as "admission numbers are unique" turn into clear messages instead of crashes.

What you should know first: CRUD with Prepared Statements in the PHP course teaches prepare(), execute() and lastInsertId() from zero, and Handling Forms covers $_POST. You also need the six tables from Designing the MySQL Database and the db() function from PHP & MySQL with PDO.

CRUD is the admission register

CRUD stands for Create, Read, Update and Delete, the four things almost every app does with its data. A school office does them with its paper admission register. The clerk writes a new entry (create), looks one up (read), corrects a spelling (update) and, when a child leaves, writes "left" in the margin instead of tearing out the page.

Here is the plan for students. Each action gets a URL, an HTTP method and one SQL statement:

ActionRequestSQL
List and searchGET /students?class_id=3&q=anSELECT ... WHERE
Show one studentGET /student?id=5SELECT ... WHERE id = :id
Add a studentGET and POST /students/newINSERT
Correct a recordGET and POST /student/edit?id=5UPDATE
Mark as leftPOST /student/leave?id=5UPDATE ... SET status = 'left'
Delete a mistakePOST /student/delete?id=9DELETE

The rule behind the middle column: reading uses GET, changing uses POST. Browsers, link previews in WhatsApp and search engine crawlers follow GET links freely, and some browsers fetch links before you click them. If GET /student/delete?id=9 deleted a row, a crawler could empty your table. A POST request is only sent when someone submits a form.

Step 1: routes that know the method

Until now, $routes in public/index.php matched only the path, so /students meant the same thing for GET and POST. We now put the method into each key. Every route from earlier lessons gets a GET prefix, and the lookup builds the same kind of key:

PHP
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';

$routes = [
    'GET /' => function (): void { /* as before */ },
    'GET /classes' => function (): void { /* as before */ },
    'GET /students' => function (): void { /* new, below */ },
    'POST /students/new' => function (): void { /* new, below */ },
    // ...
];

$handler = $routes["{$method} {$path}"] ?? null;

A request that matches no key, such as GET /student/delete?id=9, still falls through to the 404 page, so a link can never trigger a delete.

Step 2: one file for student queries

Keep SQL out of the route closures. Create src/students.php, add require APP_ROOT . '/src/students.php'; to src/bootstrap.php, and start with the two read functions:

PHP
<?php
declare(strict_types=1);

/** Active students, optionally in one class and matching part of a name. */
function search_students(?int $classId, string $name): array
{
    $sql = 'SELECT s.id, s.admission_no, s.full_name, c.grade, c.section
              FROM students s
              JOIN classes c ON c.id = s.class_id
             WHERE s.status = :status';
    $params = ['status' => 'active'];

    if ($classId !== null) {
        $sql .= ' AND s.class_id = :class_id';
        $params['class_id'] = $classId;
    }
    if ($name !== '') {
        // ! is our escape character, so % and _ typed by the user are plain text
        $sql .= " AND s.full_name LIKE :name ESCAPE '!'";
        $params['name'] = '%' . strtr($name, ['!' => '!!', '%' => '!%', '_' => '!_']) . '%';
    }

    $stmt = db()->prepare($sql . ' ORDER BY c.grade, c.section, s.full_name');
    $stmt->execute($params);
    return $stmt->fetchAll();
}

function find_student(int $id): ?array
{
    $stmt = db()->prepare(
        'SELECT s.*, c.grade, c.section
           FROM students s
           JOIN classes c ON c.id = s.class_id
          WHERE s.id = :id'
    );
    $stmt->execute(['id' => $id]);
    return $stmt->fetch() ?: null;
}

Building SQL in pieces is fine when the pieces are fixed text. The WHERE clause grows only with strings written in our code, like ' AND s.class_id = :class_id'. Values from the visitor never touch $sql; they go into $params and travel separately. That is the whole rule of prepared statements.

LIKE needs the wildcards in the value, not in the SQL. Beginners write LIKE '%:name%', but a placeholder inside quotes is just text, so it never gets replaced. Put the % signs around the value instead. Then there is a second trap: % and _ typed by the user are wildcards too. We tested this. Before escaping, a search for % matched all 9 students; with the strtr() line, it matched 0, because nobody's name contains a percent sign. ESCAPE '!' tells MySQL that ! marks the next character as plain text. We chose ! because a backslash has different rules in MySQL and SQLite strings.

The write functions follow the same pattern. insert_student() returns the new row's id from lastInsertId():

PHP
function insert_student(array $data): int
{
    $stmt = db()->prepare(
        'INSERT INTO students
            (admission_no, full_name, date_of_birth, class_id, guardian_name, guardian_phone)
         VALUES
            (:admission_no, :full_name, :date_of_birth, :class_id, :guardian_name, :guardian_phone)'
    );
    $stmt->execute($data);
    return (int) db()->lastInsertId();
}

update_student(int $id, array $data) runs UPDATE students SET ... WHERE id = :id with $data + ['id' => $id]. mark_student_left() and delete_student() are one prepared statement each.

Step 3: check the input before writing

The browser's required attribute is a convenience for honest users. Anyone can send a POST request with curl and skip it, so the server checks again. validate_student() in the same file trims each field, returns the cleaned data, and collects one message per broken field:

PHP
function validate_student(array $input, array $classIds): array
{
    $text = fn(string $key): string => is_string($input[$key] ?? null) ? trim($input[$key]) : '';

    $data = [
        'admission_no'   => strtoupper($text('admission_no')),
        'full_name'      => $text('full_name'),
        'date_of_birth'  => $text('date_of_birth'),
        'class_id'       => filter_var($text('class_id'), FILTER_VALIDATE_INT) ?: 0,
        'guardian_name'  => $text('guardian_name'),
        'guardian_phone' => $text('guardian_phone'),
    ];
    $errors = [];

    if (!preg_match('/^SP-\d{4}-\d{4}$/', $data['admission_no'])) {
        $errors['admission_no'] = 'Use the format SP-2026-0042.';
    }
    $dob = DateTimeImmutable::createFromFormat('!Y-m-d', $data['date_of_birth']);
    if ($dob === false || $dob->format('Y-m-d') !== $data['date_of_birth']) {
        $errors['date_of_birth'] = 'Enter a real date.';
    }
    if (!in_array($data['class_id'], $classIds, true)) {
        $errors['class_id'] = 'Choose a class from the list.';
    }
    if (!preg_match('/^[6-9]\d{9}$/', $data['guardian_phone'])) {
        $errors['guardian_phone'] = 'Enter a 10-digit mobile number.';
    }
    // full_name and guardian_name: 2 to 100 characters, checked with mb_strlen()

    return [$data, $errors];
}

The is_string() check matters: a tampered form can send full_name[]=x, which PHP turns into an array, and trim() on an array throws a TypeError. The date check rejects 2011-02-30, because PHP quietly rolls it over to 2 March and the formatted string no longer matches. Forms, Validation & CSRF builds a fuller validation layer and protects these forms from cross-site request forgery.

Step 4: create with Post/Redirect/Get

Now the two routes for adding a student. class_options() (also in students.php) returns [id => 'Class 10-A'] for the drop-down list.

PHP
'GET /students/new' => function (): void {
    render('student-form', [
        'title' => 'Add a student', 'action' => '/students/new',
        'student' => [], 'errors' => [], 'classes' => class_options(),
    ]);
},
'POST /students/new' => function (): void {
    $classes = class_options();
    [$data, $errors] = validate_student($_POST, array_keys($classes));
    if ($errors === []) {
        try {
            redirect('/student?id=' . insert_student($data));
        } catch (PDOException $e) {
            if ($e->getCode() !== '23000') {
                throw $e;
            }
            $errors['admission_no'] = 'Another student already has this admission number.';
        }
    }
    http_response_code(422);
    render('student-form', [
        'title' => 'Add a student', 'action' => '/students/new',
        'student' => $data, 'errors' => $errors, 'classes' => $classes,
    ]);
},

The new helper redirect() in src/helpers.php sends a Location header with status 303 See Other and stops the script. This is the Post/Redirect/Get pattern. After a successful POST, the browser is told to GET the student's page. If the clerk then presses F5, the browser reloads that page instead of sending the form again, so nobody gets admitted twice.

When validation fails, the form comes back with status 422 (Unprocessable Content), the typed values, and the messages. Notice how the duplicate check works. We do not run a SELECT first to see whether the admission number exists. Two clerks could both pass that check at the same moment. Instead we let the unique key uq_students_admission_no decide, and catch the error. getCode() on a PDOException returns the SQLSTATE, and 23000 means an integrity rule was broken. On MySQL, $e->errorInfo[1] holds the exact number if you need it: 1062 for a duplicate key, 1451 for a row other rows still point to.

Real responses from our test copy:

Terminal
curl -s -o /dev/null -w "%{http_code} %{redirect_url}\n" -X POST http://shiksha.test/students/new \
  -d admission_no=sp-2026-0035 --data-urlencode "full_name=Kabir Rastogi" -d date_of_birth=2011-06-21 \
  -d class_id=3 --data-urlencode "guardian_name=Manoj Rastogi" -d guardian_phone=9800000035
Output
303 http://shiksha.test/student?id=9

The lowercase sp- was cleaned to SP-2026-0035 by strtoupper(). Sending SP-2026-0031 (Aarav's number) returned 422 with "Another student already has this admission number."

Step 5: the form template

templates/student-form.php serves both "add" and "edit". Each field prints its old value through e(), so a name like D'Souza or a typed <script> comes back as harmless text:

PHP
<?php foreach ($fields as $field => [$label, $type]): ?>
            <p>
                <label for="<?= $field ?>"><?= e($label) ?></label>
                <input id="<?= $field ?>" name="<?= $field ?>" type="<?= $type ?>"
                       value="<?= e($student[$field] ?? '') ?>" required>
<?php if (isset($errors[$field])): ?>
                <strong class="error"><?= e($errors[$field]) ?></strong>
<?php endif; ?>
            </p>
<?php endforeach; ?>

$fields is a fixed array in the template, so $field needs no escaping. Below is the real HTML our server returned for a bad submission, with a small stylesheet added. Open it in the editor. Notice that the browser shows the date box empty: 2011-02-30 is not a valid date, so the browser drops it, which is one more reason the server must check too.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Add a student | ShikshaPortal</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    label { display: block; font-weight: 600; }
    .error { color: #b00020; display: block; }
  </style>
</head>
<body>
  <h1>Add a student</h1>
  <form method="post" action="/students/new">
    <p>
      <label for="admission_no">Admission no.</label>
      <input id="admission_no" name="admission_no" type="text" value="SP-26-35" required>
      <strong class="error">Use the format SP-2026-0042.</strong>
    </p>
    <p>
      <label for="full_name">Full name</label>
      <input id="full_name" name="full_name" type="text" value="Kabir Rastogi" required>
    </p>
    <p>
      <label for="date_of_birth">Date of birth</label>
      <input id="date_of_birth" name="date_of_birth" type="date" value="2011-02-30" required>
      <strong class="error">Enter a real date.</strong>
    </p>
    <p>
      <label for="guardian_phone">Guardian mobile</label>
      <input id="guardian_phone" name="guardian_phone" type="tel" value="98000" required>
      <strong class="error">Enter a 10-digit mobile number.</strong>
    </p>
    <button>Save</button>
  </form>
</body>
</html>

Step 6: update, mark as left, delete

The edit routes mirror the create routes. GET /student/edit?id=5 loads the row with find_student() and fills the same form. POST /student/edit?id=5 validates, calls update_student(), and redirects to /student?id=5. Both answer 404 when the id is not a positive integer or no row exists, just like /class?id= did.

The database design said students who leave are never deleted, because their marks are part of the school's records. So the student page has two buttons, each inside its own small POST form:

PHP
'POST /student/delete' => function () use ($idFromQuery, $notFound): void {
    $id = $idFromQuery();
    if ($id === null || find_student($id) === null) {
        $notFound('No student has that id.');
        return;
    }
    try {
        delete_student($id);
    } catch (PDOException $e) {
        if ($e->getCode() !== '23000') {
            throw $e;
        }
        http_response_code(409);
        render('error', [
            'title' => 'Cannot delete',
            'message' => 'This student already has marks. Mark them as left instead.',
        ]);
        return;
    }
    redirect('/students');
},

$idFromQuery and $notFound are two small closures defined above $routes, shared by the student routes. "Mark as left" runs UPDATE students SET status = 'left', and the list only shows active students. "Delete" is for a row typed by mistake. The foreign key fk_marks_student refuses to delete a student who has marks, and we turn that refusal into a 409 Conflict page. We sent four requests to our test copy:

Terminal
for req in "POST /student/delete?id=5" "POST /student/delete?id=9" \
           "GET /student/delete?id=6" "POST /student/leave?id=8"; do
  set -- $req
  curl -s -o /dev/null -X "$1" -w "$1 $2 %{http_code}\n" "http://shiksha.test$2"
done
Output
POST /student/delete?id=5 409
POST /student/delete?id=9 303
GET /student/delete?id=6 404
POST /student/leave?id=8 303

Aarav (id 5) has five marks, so the delete was refused. Kabir's new row (id 9) had no marks and was deleted. The GET request found no route and changed nothing. Meera (id 8) was marked as left, and the Class 10-A list dropped from 4 to 3 students. The database protected the records even though the PHP code never checked for marks itself.

Advanced: many writes, one transaction

Entering marks means five INSERTs for one student, one per subject. If the third fails, you do not want two subjects saved and three missing. A transaction groups statements so they all succeed or none do. src/marks.php:

PHP
function save_exam_marks(int $studentId, int $examId, array $marks): void
{
    $pdo = db();
    $stmt = $pdo->prepare(
        'INSERT INTO marks (student_id, exam_id, subject_id, marks_obtained)
         VALUES (:student_id, :exam_id, :subject_id, :marks_obtained)'
    );

    $pdo->beginTransaction();
    try {
        foreach ($marks as $subjectId => $obtained) {
            $stmt->execute([
                'student_id' => $studentId, 'exam_id' => $examId,
                'subject_id' => $subjectId, 'marks_obtained' => $obtained,
            ]);
        }
        $pdo->commit();
    } catch (Throwable $e) {
        $pdo->rollBack();
        throw $e;
    }
}

The statement is prepared once and executed five times with different values. We tried Ananya's Annual marks with Mathematics typed as 105, then with 95:

Output
Not saved: one mark broke a rule, so none were kept
Annual marks in the table: 0
Annual marks in the table: 5

The CHECK constraint rejected 105, and rollBack() removed the two marks already inserted. Transactions explains the theory.

Common mistakes

  • Deleting or changing data with a GET link. Crawlers and link previews will trigger it. Use a POST form.
  • LIKE '%:name%'. The placeholder inside quotes is never replaced. Put % in the value.
  • Checking for duplicates with a SELECT first. Two requests can pass the check together. Let the unique key decide and catch 23000.
  • UPDATE or DELETE without WHERE. Every row changes. Read the statement twice before running it.
  • Rendering a page straight after a successful POST. Refreshing sends the form again. Redirect with 303.

Interview questions

1. Why should state-changing actions use POST rather than GET?

GET requests are meant to be safe to repeat, so browsers prefetch them, crawlers follow them and caches store them. An action like delete behind a GET link can run without the user meaning to. POST requests are only sent when a form is submitted, and they are not cached or prefetched.

2. What is the Post/Redirect/Get pattern?

After handling a successful POST, the server answers with a redirect (303 See Other) to a normal page, and the browser loads it with GET. Refreshing then repeats the harmless GET, not the form submission, so records are not created twice.

3. How do you search with LIKE safely using PDO?

Bind the whole pattern as the value, such as '%' . $term . '%', never put the placeholder inside quotes. Also escape % and _ in the user's term with an ESCAPE character, otherwise those characters act as wildcards and change the search.

4. Why catch a duplicate-key error instead of checking with SELECT first?

A check-then-insert has a race: two requests can both see "no duplicate" and both insert. A unique key makes the database the single judge. The second insert fails with SQLSTATE 23000, and the app turns that into a friendly message.

Key points

  • Put the HTTP method in each route key: reads use GET, changes use POST forms.
  • Keep SQL in functions such as search_students(); values go only into the parameters array.
  • For LIKE, add % to the bound value and escape % and _ with ESCAPE.
  • Validate on the server, re-show the form with status 422, and redirect with 303 after success.
  • Let unique and foreign keys protect the data; catch SQLSTATE 23000 and show a clear message.
  • Students are marked as left, not deleted; use a transaction when several writes belong together.

Exercise

Add CRUD for subjects. GET /subjects lists them, GET and POST /subjects/new add one, and GET and POST /subject/edit?id= correct one. A code must be 2 to 10 capital letters (such as CS for Computer Science) and a name 2 to 60 characters. Use prepared statements, Post/Redirect/Get, and show "That code is already used" when the unique key uq_subjects_code is broken. Then explain why there is no delete route.

Show solution
PHP
function insert_subject(string $code, string $name): int
{
    $stmt = db()->prepare('INSERT INTO subjects (code, name) VALUES (:code, :name)');
    $stmt->execute(['code' => $code, 'name' => $name]);
    return (int) db()->lastInsertId();
}

'POST /subjects/new' => function (): void {
    $code = strtoupper(trim((string) ($_POST['code'] ?? '')));
    $name = trim((string) ($_POST['name'] ?? ''));
    $errors = [];
    if (!preg_match('/^[A-Z]{2,10}$/', $code)) {
        $errors['code'] = 'Use 2 to 10 capital letters.';
    }
    if (mb_strlen($name) < 2 || mb_strlen($name) > 60) {
        $errors['name'] = 'Enter a name of 2 to 60 characters.';
    }
    if ($errors === []) {
        try {
            insert_subject($code, $name);
            redirect('/subjects');
        } catch (PDOException $e) {
            if ($e->getCode() !== '23000') {
                throw $e;
            }
            $errors['code'] = 'That code is already used.';
        }
    }
    http_response_code(422);
    render('subject-form', ['title' => 'Add a subject', 'code' => $code, 'name' => $name, 'errors' => $errors]);
},

The edit route is the same with UPDATE subjects SET code = :code, name = :name WHERE id = :id and a 404 for unknown ids. There is no delete route because marks points to subjects with a foreign key, and old report cards must keep their subject names.

Quick Quiz

1. Why is POST /student/delete safer than a link to GET /student/delete?id=9?

2. A search uses LIKE :name with the value '%' . $term . '%' and no escaping. What does searching for _ return?

3. After a successful insert, ShikshaPortal sends status 303. Why?

4. Deleting Aarav fails with SQLSTATE 23000. What stopped it?

Learn LAMP Stack with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call