Let's think about this for a sec
This lesson is designed to combine the skills you learned in the Forms, Validation, Arrays, and DB Connect/Select/Insert chapters. It's a step up from Lesson 1 — the logic is more involved, and you'll need to handle input validation, array manipulation, and database queries all at once. Build and run each task in your own project folder. The focus is on using $_SERVER['REQUEST_METHOD'] and prepared statements correctly.
Exercises
Task 1: Build an HTML form with name and email fields, then validate the POSTed data — check that it isn't empty and use filter_var(FILTER_VALIDATE_EMAIL) — if there are errors, loop through an array of error messages and display them. Task 2: Write a function that takes an associative array called students (name => score) and returns "Fail" for scores under 60 and "Pass" otherwise. Task 3: Use a prepared statement (mysqli or PDO) to look up a single user from the users table by a WHERE condition on the email column, then echo their data — if the table doesn't exist yet, it's fine to just write the schema (id, name, email) as a comment.
Code example
<?php
// Task 1
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$errors = [];
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");
if ($name === "") $errors[] = "Name is required";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Invalid email";
foreach ($errors as $err) {
echo $err . "<br>";
}
}
// Task 2
$students = ["Su" => 75, "Kyaw" => 45, "Mya" => 88];
function checkResult($students) {
foreach ($students as $name => $score) {
$status = ($score < 60) ? "Fail" : "Pass";
echo $name . ": " . $status . "<br>";
}
}
checkResult($students);
// Task 3 (schema: users(id, name, email))
$stmt = $conn->prepare("SELECT id, name, email FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row["name"] . " - " . $row["email"];
}
?>If all 3 tasks succeed: submitting an invalid form shows a list of error messages, the students array produces a Pass/Fail status list, and the user matching that email is found in the database with their name/email printed out.Give it 5 minutes
Write Task 3 first using plain string concatenation ($conn->query()), then comment it out and write the prepared statement version — spend 5 minutes working out for yourself why the prepared statement version is safer.
A quick word of caution
In a real project, never put user input directly into a database query string — always use prepared statements (bind_param) instead. Build this habit right from the start and you'll significantly cut the odds of a security bug making it into production.