Thuta Learning
PHP
ExercisesProgrammingBeginner

Exercises: Forms, Arrays & Database

PHPLesson 3650 min

What you'll walk away with

  • Validate form-shaped arrays (missing keys, wrong types, blank values) and return all errors as data
  • Process an associative array with foreach and array functions, including empty and boundary cases
  • Look up and insert rows with prepared statements and turn constraint errors into friendly messages
  • Normalise input with trim and lowercase so a lookup behaves the same on SQLite and MySQL

Explain it simply

Explain it simply

This lesson combines three skills from the course: reading form data, working with arrays and talking to a database. Picture them as three stations on an assembly line: form data arrives and is checked, then it is shaped and counted as an array, and finally it is stored in or looked up from a table.

Every exercise below is one station, and the last one connects them all. As in the first exercise lesson you write the code yourself, but this time there is no browser: a form submission is simply an array that you build by hand.

Problem → Why → Solution

The problem: every stage trusts the one before it

Code that goes from a form to a database is where beginners meet their first real bugs, because every stage trusts the one before it. Look at the code below. It reads $_POST['email'] without checking that the key exists (an "Undefined array key" warning is possible). It pastes the value straight into a SQL string (injection). It prints the result without escaping.

That code "works" with the one email address the developer types. The problems appear only when someone submits an empty form, sends an array such as name[], or enters an email containing a quote.

trusting-everything.php
<?php
// Form handling, validation and SQL, all trusting the browser.
$email = $_POST['email'];
$result = $conn->query("SELECT * FROM users WHERE email = '$email'");
while ($row = $result->fetch_assoc()) {
    echo $row['name'] . ' - ' . $row['email'] . '<br>';
}

Why does this keep happening?

Each stage assumes that the data coming from the stage before is already safe, when in fact no stage has checked it. The fix is to write every stage as its own function with its own promise (input and output) and to feed bad input to reading, validating and querying yourself.

Core concept: every stage is its own function

The main technique in these exercises is writing every stage as its own function. Because each function has a clear input and output, you can hunt for bugs just by calling it with a prepared array. There are five stages.

1. Read defensively

Read with $post['name'] ?? '' and check the type with is_string(). A missing key raises an Undefined array key warning, and an array such as name[]=x can make trim() throw a TypeError.

2. Validate and collect every error

Use filter_var() with FILTER_VALIDATE_EMAIL and FILTER_VALIDATE_INT (min_range, max_range). filter_var allows surrounding spaces such as ' 25 ' and accepts '+7', but it rejects '007' and '25.0'. Do not stop at the first error; collect them all.

3. Process arrays on purpose

Use foreach ($scores as $name => $score) for an associative array. Decide the boundary deliberately (if 60 passes, use >=). Guard the empty array first, because max([]) throws a ValueError.

4. Query with a prepared statement

Call prepare(), execute() and fetch(). fetch() returns false when no row matches, so convert that to an explicit null yourself and the calling code will not read ['name'] from false.

5. Normalise before storing and looking up

Trim and lowercase the email before you store it, and do the same when you look it up. The usual MySQL collations ignore letter case while SQLite's default does not, so normalising in PHP makes the behaviour the same everywhere. Keep a UNIQUE constraint as well so duplicates cannot appear.

StageToolEdge case to test
Reading?? and is_string()Missing key, name[] array
Validatingfilter_var, trimBlank, '2x', ' 25 '
Arraysforeach =>, array_count_values, maxEmpty array, a tie, the mark of 60
Databaseprepare, execute, fetchNo row found, a value containing a quote
ConstraintsUNIQUE, CHECKA duplicate email in a different case
Mental model: a line with four stations
  1. Read fields defensively with ??
  2. Validate and collect every error
  3. Shape the data with array functions
  4. Query with prepared statements only

When one stage breaks, call just that function with a prepared array. There is no need to touch the other stages.

General pattern

php
<?php
function handleForm(array $post, PDO $db): array
{
    // 1. read every field with ?? and check its type
    // 2. collect all validation problems in an array
    // 3. stop and return them when the array is not empty
    // 4. run the prepared statement with the clean values
    // 5. return the result as data for the page to display
}

The form handler takes an array and a database object, reads, validates, decides whether to stop, runs the query and returns the result as data.

Reference solutions for the three tasks and the full path

This file holds Task 1 (validate a signup form), Task 2 (a pass/fail report), Task 3 (find a user by email) and Task 4 (register), which connects them all. Write them yourself first and compare afterwards. The form submissions are broken one detail at a time from a shared starting array with array_replace(). The database is SQLite, and a deeper section below shows how the same lookup reads with MySQLi.

forms-arrays-db.php
<?php
declare(strict_types=1);

// Task 1: validate a signup form. $post stands in for $_POST.
function validateSignup(array $post): array
{
    $name = $post['name'] ?? '';
    $email = $post['email'] ?? '';
    $name = is_string($name) ? trim($name) : '';
    $email = is_string($email) ? trim($email) : '';

    $errors = [];
    if ($name === '') {
        $errors['name'] = 'Name is required';
    }
    if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        $errors['email'] = 'Invalid email';
    }
    $range = ['options' => ['min_range' => 13, 'max_range' => 120]];
    if (filter_var($post['age'] ?? '', FILTER_VALIDATE_INT, $range) === false) {
        $errors['age'] = 'Age must be a whole number from 13 to 120';
    }
    return $errors;
}

// Task 2: pass or fail from an associative array of scores.
function gradeReport(array $scores, int $passMark = 60): array
{
    $results = [];
    foreach ($scores as $name => $score) {
        $results[$name] = $score >= $passMark ? 'Pass' : 'Fail';
    }
    return $results;
}

function summarize(array $scores, int $passMark = 60): array
{
    if ($scores === []) {
        return ['passed' => 0, 'failed' => 0, 'average' => null, 'top' => null];
    }
    $counts = array_count_values(gradeReport($scores, $passMark));
    return [
        'passed' => $counts['Pass'] ?? 0,
        'failed' => $counts['Fail'] ?? 0,
        'average' => round(array_sum($scores) / count($scores), 1),
        'top' => array_keys($scores, max($scores), true)[0],
    ];
}

// Task 3: look up one user with a prepared statement.
function findUserByEmail(PDO $pdo, string $email): ?array
{
    $stmt = $pdo->prepare('SELECT id, name, email FROM users WHERE email = :email');
    $stmt->execute(['email' => strtolower(trim($email))]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row === false ? null : $row;
}

// Task 4: the whole path, form to database.
function register(array $post, PDO $pdo): array
{
    $errors = validateSignup($post);
    if ($errors !== []) {
        return ['ok' => false, 'errors' => $errors];
    }

    $stmt = $pdo->prepare(
        'INSERT INTO users (name, email, age) VALUES (:name, :email, :age)'
    );
    try {
        $stmt->execute([
            'name' => trim($post['name']),
            'email' => strtolower(trim($post['email'])),
            'age' => (int) $post['age'],
        ]);
    } catch (PDOException $e) {
        if ($e->getCode() === '23000') { // UNIQUE or CHECK refused the row
            return ['ok' => false, 'errors' => ['email' => 'Email already registered']];
        }
        throw $e;
    }
    return ['ok' => true, 'errors' => []];
}

$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT NOT NULL UNIQUE,
    age INTEGER NOT NULL CHECK (age BETWEEN 13 AND 120)
)');

echo "== Tasks 1 and 4: signup ==\n";
$good = ['name' => 'Su', 'email' => 'su@example.com', 'age' => '25'];
$forms = [
    'valid'                  => ['name' => 'Aung', 'email' => 'Aung@Example.com'] + $good,
    'same email, other case' => array_replace($good, ['email' => 'aung@example.com']),
    'everything wrong'       => ['name' => '   ', 'email' => 'nope', 'age' => '7'],
    'no fields at all'       => [],
    'array instead of text'  => array_replace($good, ['name' => ['x']]),
    'age is not a number'    => array_replace($good, ['age' => '2x']),
];
foreach ($forms as $label => $post) {
    $result = register($post, $pdo);
    $text = $result['ok'] ? 'registered' : implode(' | ', $result['errors']);
    echo str_pad($label, 24) . $text . "\n";
}

echo "\n== Task 2: grades ==\n";
$students = ['Su' => 75, 'Kyaw' => 45, 'Mya' => 88, 'Hla' => 60];
foreach (gradeReport($students) as $name => $status) {
    echo "$name: $status\n";
}
echo 'summary: ' . json_encode(summarize($students)) . "\n";
echo 'empty class: ' . json_encode(summarize([])) . "\n";

echo "\n== Task 3: lookup ==\n";
$found = findUserByEmail($pdo, ' AUNG@example.com ');
echo 'found: ' . ($found ? "{$found['name']} <{$found['email']}>" : 'nobody') . "\n";
$attack = findUserByEmail($pdo, "x' OR '1'='1");
echo 'injection attempt: ' . ($attack ? 'matched a user!' : 'no user matched') . "\n";

Code breakdown

  1. Defensive read$name = is_string($name) ? trim($name) : '';

    When a field is missing, ?? '' supplies an empty string. For an array such as name[]=x, is_string() is false, so it is treated as blank and trim() is never called with an array, which is why "array instead of text" gets "Name is required".

  2. Validation with a range$range = ['options' => ['min_range' => 13, 'max_range' => 120]];

    FILTER_VALIDATE_INT returns the value only when it is a whole number inside the range, otherwise false. That is why '7', '2x' and a missing age all get the age error.

  3. A deliberate boundary$results[$name] = $score >= $passMark ? 'Pass' : 'Fail';

    Because of >=, Hla's mark of 60 is a Pass; with > it would be a Fail. The requirement decides which one is right, so always test this boundary.

  4. Counting with an array function$counts = array_count_values(gradeReport($scores, $passMark));

    array_count_values() counts how often 'Pass' and 'Fail' appear. If everyone passes there is no 'Fail' key, which is why ?? 0 is used further down.

  5. An explicit "not found"return $row === false ? null : $row;

    fetch() returns false when no row matches. Converting that to null, with a ?array return type, lets the caller test it with a plain if ($found).

  6. Normalise before comparing$stmt->execute(['email' => strtolower(trim($email))]);

    Looking up ' AUNG@example.com ' is trimmed and lowercased, so it finds the row stored from Aung@Example.com. register() normalised it the same way when it stored it.

  7. A constraint becomes a messageif ($e->getCode() === '23000') { // UNIQUE or CHECK refused the row

    A repeated email is refused by UNIQUE and raises a PDOException. The code catches it and returns "Email already registered", so the visitor never sees a SQL error. Any other error is rethrown.

You should see
== Tasks 1 and 4: signup ==
valid                   registered
same email, other case  Email already registered
everything wrong        Name is required | Invalid email | Age must be a whole number from 13 to 120
no fields at all        Name is required | Invalid email | Age must be a whole number from 13 to 120
array instead of text   Name is required
age is not a number     Age must be a whole number from 13 to 120

== Task 2: grades ==
Su: Pass
Kyaw: Fail
Mya: Pass
Hla: Pass
summary: {"passed":3,"failed":1,"average":67,"top":"Mya"}
empty class: {"passed":0,"failed":0,"average":null,"top":null}

== Task 3: lookup ==
found: Aung <aung@example.com>
injection attempt: no user matched

What SQLSTATE 23000 really tells you

23000 covers many kinds of constraint

SQLSTATE 23000 is used for UNIQUE, NOT NULL, CHECK and foreign-key violations alike. In register(), validation has already checked age and the other fields, so a 23000 can only mean a repeated email. If that is not true in your code, for example because validation is missing, the message "Email already registered" can be wrong. In that case look at the driver-specific error code in $e->errorInfo, or check for the duplicate separately before inserting.

Why normalise the email

By default SQLite compares text exactly, with letter case mattering. In the demo below, Aung@Example.com is stored, and a plain comparison finds 0 rows while COLLATE NOCASE finds 1. The collations MySQL tables commonly use do not distinguish letter case, but that depends on the table's collation, so check your own table. Normalising in PHP keeps the behaviour from changing when you move from one database to another.

collation.php
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->exec('CREATE TABLE users (email TEXT)');
$pdo->exec("INSERT INTO users (email) VALUES ('Aung@Example.com')");

$sql = "SELECT COUNT(*) FROM users WHERE email = 'aung@example.com'";
$exact = $pdo->query($sql)->fetchColumn();
$nocase = $pdo->query($sql . ' COLLATE NOCASE')->fetchColumn();

echo "default comparison: $exact match(es)\n";
echo "COLLATE NOCASE:     $nocase match(es)\n";
text
default comparison: 0 match(es)
COLLATE NOCASE:     1 match(es)

Edge cases in the array exercise

Calling max() with an empty array throws a ValueError in PHP 8, which is why summarize() checks for an empty class first. When two students tie for the top score, array_keys($scores, max($scores), true) returns both, and taking [0] gives the first one. Which of them you pick depends on the requirement, so decide it yourself and write it down.

array-edge-cases.php
<?php
try {
    echo max([]);
} catch (ValueError $e) {
    echo get_class($e) . ': ' . $e->getMessage() . "\n";
}

$scores = ['Su' => 88, 'Mya' => 88, 'Kyaw' => 45];
$best = array_keys($scores, max($scores), true);
echo 'first top scorer: ' . $best[0] . "\n";
echo 'all top scorers:  ' . implode(', ', $best) . "\n";
text
ValueError: max(): Argument #1 ($value) must contain at least one element
first top scorer: Su
all top scorers:  Su, Mya

The real page and the MySQLi shape

The course's earlier lessons use MySQLi. Task 3 written with MySQLi uses a ? placeholder, bind_param() and get_result(), and get_result() needs the mysqlnd driver. Do not forget that MySQLi's fetch_assoc() returns null when no row matches while PDO's fetch() returns false. Both snippets need a MySQL server or a web server, so they are not run here.

find-user-mysqli.php
<?php
// MySQLi version of Task 3. It needs a MySQL server, so it is not run here.
$stmt = $conn->prepare('SELECT id, name, email FROM users WHERE email = ?');
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc(); // null when no row matches
register-page.php
<?php
// register.php: runs on a web server, so it is not executed in this lesson.
declare(strict_types=1);

$errors = [];
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $result = register($_POST, $pdo);
    $errors = $result['errors'];
    $message = $result['ok'] ? 'Welcome aboard!' : '';
}

foreach ($errors as $error) {
    echo '<p class="error">' . htmlspecialchars($error) . "</p>\n";
}
if ($message !== '') {
    echo '<p>' . htmlspecialchars($message) . "</p>\n";
}

In real projects

In real projects

Register forms, logins, profile edits and checkouts all follow the same five stages: read, validate, shape, query, normalise. The HTML required and pattern attributes only make life easier for the visitor; anyone can send a request directly, so server-side validation is not optional. Looking a user up by email at login, counting pass and fail marks in an admin report and producing totals with GROUP BY on a dashboard are all the same shape as these exercises.

The column you search with WHERE should be indexed, and a UNIQUE constraint creates an index too. So a UNIQUE email does more than prevent duplicates: it also makes the login query fast. With tens of thousands of rows or more that difference becomes very noticeable.

Common mistakes

Common mistakes

Reading $_POST['x'] without ??

When the key is missing, PHP 8 raises an "Undefined array key" warning and uses null, which from PHP 8.1 on then triggers follow-up deprecations such as trim(null). Read with ?? '' and check is_string() as well.

Pasting the visitor's input into SQL

Writing "... WHERE email = '$email'" lets a value containing a quote change the query. The injection test in Task 3 (x' OR '1'='1) finds nothing because of the prepared statement. Repeat that test on every function you write.

Never testing the boundary value

If the requirement says "marks under 60 fail", then score < 60 is a Fail and 60 itself is a Pass. A wrong > versus >= is invisible when you just read the code; it shows up only when you deliberately put a student with exactly 60 into the data.

Not checking the result of fetch()

When no row matches, PDO's fetch() returns false. Reading $row['name'] from it makes PHP warn that it is trying to access an array offset on false (the exact wording differs between PHP releases) and gives you null. Check with === false first.

Mini challenge

Write a feedback form handler and report

Write three functions for a visitor feedback form. submitFeedback() validates a rating (1 to 5) and an optional comment (at most 200 characters) and stores them in a feedback table. averageRating() returns the average, or null when there is no data. ratingHistogram() returns the count for every star level from 1 to 5, including levels with a count of 0.

  • Validate rating with FILTER_VALIDATE_INT between 1 and 5, and return an error when the field is missing
  • Trim the comment, treat a non-string as blank, and return an error when mb_strlen exceeds 200
  • submitFeedback() returns ['ok' => bool, 'errors' => array] and uses a prepared INSERT only
  • averageRating() returns null when there are no rows, and ratingHistogram() returns an array that has every key from 1 to 5
challenge.php
<?php
declare(strict_types=1);

// $pdo already has: feedback(id, rating INTEGER CHECK 1..5, comment TEXT)

function submitFeedback(array $post, PDO $pdo): array
{
    // TODO: read rating and comment defensively with ??
    // TODO: collect errors, return ['ok' => false, 'errors' => ...] if any
    // TODO: prepared INSERT, then return ['ok' => true, 'errors' => []]
}

function averageRating(PDO $pdo): ?float
{
    // TODO: SELECT AVG(rating); null when the table is empty; round to 2 places
}

function ratingHistogram(PDO $pdo): array
{
    // TODO: start from [1 => 0, 2 => 0, ... 5 => 0], then fill in GROUP BY counts
}

Expected: Before any feedback, averageRating prints NULL. five stars, no comment and another five are stored; zero stars, not a number and empty form get the rating error and too long gets the comment error. The average is 4.33, with one 3-star entry and two 5-star entries.

Show hint

Start from array_fill_keys([1, 2, 3, 4, 5], 0) and then add the GROUP BY results, so a star level with no rows still shows 0. AVG() gives NULL when there are no rows, and fetchColumn() returns null. Cast the values you get from PDO with (int).

Show solution
challenge.php
<?php
declare(strict_types=1);

$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("CREATE TABLE feedback (
    id INTEGER PRIMARY KEY,
    rating INTEGER NOT NULL CHECK (rating BETWEEN 1 AND 5),
    comment TEXT NOT NULL DEFAULT ''
)");

function submitFeedback(array $post, PDO $pdo): array
{
    $errors = [];

    $range = ['options' => ['min_range' => 1, 'max_range' => 5]];
    $rating = filter_var($post['rating'] ?? '', FILTER_VALIDATE_INT, $range);
    if ($rating === false) {
        $errors['rating'] = 'Rating must be a whole number from 1 to 5';
    }

    $comment = $post['comment'] ?? '';
    $comment = is_string($comment) ? trim($comment) : '';
    if (mb_strlen($comment) > 200) {
        $errors['comment'] = 'Comment must be 200 characters or fewer';
    }

    if ($errors !== []) {
        return ['ok' => false, 'errors' => $errors];
    }

    $stmt = $pdo->prepare(
        'INSERT INTO feedback (rating, comment) VALUES (:rating, :comment)'
    );
    $stmt->execute(['rating' => $rating, 'comment' => $comment]);
    return ['ok' => true, 'errors' => []];
}

function averageRating(PDO $pdo): ?float
{
    $average = $pdo->query('SELECT AVG(rating) FROM feedback')->fetchColumn();
    return $average === null ? null : round((float) $average, 2);
}

function ratingHistogram(PDO $pdo): array
{
    $counts = array_fill_keys([1, 2, 3, 4, 5], 0);
    $rows = $pdo->query('SELECT rating, COUNT(*) AS n FROM feedback GROUP BY rating');
    foreach ($rows as $row) {
        $counts[(int) $row['rating']] = (int) $row['n'];
    }
    return $counts;
}

echo 'before any feedback: ' . var_export(averageRating($pdo), true) . "\n";

$tests = [
    'five stars'   => ['rating' => '5', 'comment' => '  Loved it  '],
    'no comment'   => ['rating' => '3'],
    'another five' => ['rating' => '5', 'comment' => 'Great'],
    'zero stars'   => ['rating' => '0'],
    'not a number' => ['rating' => 'five'],
    'too long'     => ['rating' => '4', 'comment' => str_repeat('x', 201)],
    'empty form'   => [],
];
foreach ($tests as $label => $post) {
    $result = submitFeedback($post, $pdo);
    $text = $result['ok'] ? 'stored' : implode(' | ', $result['errors']);
    echo str_pad($label, 14) . $text . "\n";
}

echo 'average: ' . averageRating($pdo) . "\n";
foreach (ratingHistogram($pdo) as $stars => $count) {
    printf("%d star: %-3s (%d)\n", $stars, str_repeat('#', $count), $count);
}

Quick quiz 1 / 3

A form arrives without the email field. What happens in PHP 8 when $email = $_POST['email']; runs?

Quick quiz 2 / 3

What does filter_var('007', FILTER_VALIDATE_INT) return?

Quick quiz 3 / 3

The users table has a UNIQUE email, and PHP applies strtolower(trim()) to the email before storing it and again when looking it up. Why?

What to remember

  • Read form data with ?? plus is_string(), validate with filter_var and return all errors as data
  • In array exercises deliberately test the boundary (a mark of 60), an empty array and a tie
  • Look rows up with prepared statements and turn fetch()'s false into an explicit null
  • Trim and lowercase emails and protect them with UNIQUE; remember that SQLSTATE 23000 covers many kinds of constraint

PHP Language Reference — PHP Documentation Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Exercises: Forms, Arrays & Database | Thuta Learning