IP622 · Internet Programming 622

One-page revision site

Internet Programming 622 Study Hub

A dark, readable study page for the supplied guide: PHP forms, request handling, cookies, sessions, file operations, SQL, MySQL connections, and local XAMPP execution.

Definitions Correct patterns Exam traps Security risks Architecture

Internet Programming Test · Topics 1 & 2

Open-book index and concise reference based on the Internet Programming 622 Study Guide. Start with a task below, then follow its link to the fuller explanation in General Module Content.

Confirmed scope: Topic 1, “PHP and HTML Form” (study guide PDF pp. 9–41), and Topic 2, “Session Controls and Cookies” (pp. 42–58). Open the supplied study guide PDF. Subtopic labels below follow its contents. The “Supporting practice” notes are useful coding safeguards; they are not additional confirmed test coverage.

Topic Index and Quick Reference

Choose a subtopic; each quick point opens its fuller explanation.

Study guide topicSubtopicQuick pointFull explanation
1 · PHP and HTML FormWeb foundations (listed outcomes)Know the browser/server request cycle, standards and accessibility, HTTP/HTTPS/FTP, URLs/URIs/DNS, responsive design, and ethical handling of information.Topic 1 foundations
Form structure and controlsUse action for the receiver, method for GET/POST, and each control’s name as the submitted key.How forms work · GET vs POST
Read submitted dataMatch the form method to $_GET or $_POST; check optional keys before reading.Request superglobals · Empty and unselected controls
Validate and display safelyValidate on the server, escape output for HTML, and never echo a password.Security · Validation and redisplay
2 · Session Controls and CookiesState and query stringsHTTP requests are independent; carry only small, non-sensitive state in a query string.Stateless HTTP
Create, read, delete cookiesCookies live in the browser and return with later requests; set them before page output.Cookies
Start, use, and end sessionsStart the session before output, store values in $_SESSION, and clear data on logout.Sessions · Compare cookies and sessions
Topic 2 · ApplyCombine state methodsUse session data for current visit state; use a cookie for a small preference that should persist.Combining cookies and sessions · Study guide tasks
Clickable Subtopic Notes

Topic 1 · Web foundations listed in the learning outcomes

Browsers request resources from servers using protocols: HTTP transfers web pages, HTTPS adds transport encryption, and FTP transfers files. A URI identifies a resource; a URL gives its location/access method; DNS maps a domain name to an IP address. Web standards support consistent behavior and accessibility; universal design aims to make content usable by people with varied abilities and devices. Responsive design adapts layouts to screen sizes. Treat personal data carefully and keep published information accurate. The study guide lists these outcomes at the start of Topic 1 but develops the remaining pages primarily through forms. Read the concise foundations note.

Topic 1 · Form structure and controls

A browser sends successful controls (those with a name) to the URL in action. GET places values in the URL query string; POST places them in the request body. Radio choices share a name; a checkbox or unselected radio sends no key. Read how forms work · Compare GET and POST.

Topic 1 · Request handling and missing fields

PHP exposes submitted keys through $_GET or $_POST. A text box left blank is usually sent as an empty string, but an unselected checkbox/radio is omitted. Use isset() to test presence and handle missing keys before access. Read request data · Review empty-field behavior.

Topic 1 · Validation, security, and redisplay

Server-side validation checks required values, type, format, and allowed range. Escape user text when inserting it into HTML to reduce XSS risk; validation does not replace escaping. Preserve valid values on redisplay and never display or store plain-text passwords. Read security guidance · Follow the validation flow.

Topic 2 · State and query strings

HTTP does not remember one request when the next begins. Query strings can carry small, visible values; cookies store browser-side values; sessions keep associated data server-side. Read the state overview.

Topic 2 · Cookie lifecycle

setcookie() asks the browser to store a cookie. The browser returns it on a later request through $_COOKIE, so a newly set cookie should not be expected in $_COOKIE during the same request. To delete it, send the same name/path with an expiry in the past. Cookies can be disabled or changed by the user; do not store secrets in them. Read cookie details.

Topic 2 · Session lifecycle

Call session_start() before output on every page that reads or writes session data. Store values in $_SESSION. session_destroy() removes server-side session data; for a complete logout, clear the session array and expire the session cookie as well. Read session details · Compare storage and use.

Topic 2 · Combine state methods

Use session state for a login or multi-page form during a visit. A cookie may remember a non-sensitive preference across visits; validate allowed values before use. Read the combined pattern · Open the guide’s review tasks.

Supporting practice (not confirmed test scope): modern deployments should use HTTPS, secure/HttpOnly/SameSite cookie settings, CSRF protections for state-changing requests, and password hashing for authentication. These are prudent implementation controls; the cited Topic 1–2 outline does not list each as examinable coverage.

Exam Focus Areas

Confirmed exam focus areas will be added here once the assessment coverage is available.

Coming soon

Exam focus areas are coming soon

The current exam-focus content has been cleared and will be updated when the confirmed focus areas are provided.

Topic 1: PHP and HTML Forms

Forms are the bridge between browser input and PHP processing. The guide moves from basic form structure to request methods, superglobals, security, empty field handling, dynamic forms, and validation.

form action GET and POST superglobals empty controls XSS prevention validation helpers

1.0 Web Foundations Listed in the Study Guide Outcomes

Scope note: the Topic 1 opening page lists these outcomes (study guide PDF p. 9); the detailed Topic 1 material that follows concentrates on HTML forms and PHP form processing. Treat this as a concise orientation to the stated outcomes, with detail depth limited by the supplied guide.

TermKey point
Browser and serverThe browser requests a resource; the server responds. PHP runs on the server and can produce HTML for the browser.
HTTP / HTTPS / FTPHTTP transfers web requests and responses; HTTPS protects HTTP traffic with TLS; FTP is a file-transfer protocol.
URI, URL, DNSA URI identifies a resource; a URL locates/accesses it; DNS resolves domain names to IP addresses used for routing.
Standards and universal designStandards support consistent behavior across browsers/devices. Universal design aims for usability across different abilities and circumstances; use semantic structure, labels, text alternatives, and keyboard access.
Responsive and progressive designResponsive layouts adapt to screen sizes. Progressive enhancement starts with core accessible content and adds capabilities where available.
EthicsRespect privacy, collect/use personal information responsibly, and keep web content accurate.

1.1 How HTML Forms Work

A web form is a collection of controls inside a <form> element. Typical controls include text fields, passwords, checkboxes, radio buttons, file selectors, hidden fields, select lists, multi-select boxes, text areas, submit buttons, and reset buttons.

Browser form Submit button HTTP request PHP handler
<form action="form_handler.php" method="post">
	<label for="email">Email</label>
	<input type="email" name="email" id="email">
	<button type="submit">Send</button>
</form>

1.2 GET vs POST

The form action says where the data goes. The form method says how it is sent. GET places values in the URL, so use it for non-sensitive searches and bookmarkable requests. POST sends data in the request body and suits submissions that process or change data. POST does not encrypt data; use HTTPS to protect traffic in transit.

Method Where Data Appears Best Fit Watch Out
GET URL query string Small requests, links, searches, bookmarkable pages Visible in the address bar and limited by URL length
POST Request body Submissions that process or change data; larger request bodies POST alone does not encrypt data; use HTTPS for transport protection

1.3 Capturing Form Data With PHP

PHP uses superglobal arrays to expose request data in any scope. The field name becomes the array key, and the submitted value becomes the array value.

  • $_GET stores form values sent with method="get".
  • $_POST stores form values sent with method="post".
  • $_REQUEST combines GET, POST, and COOKIE values, so it can be ambiguous.
$email = $_POST["emailAddress"];
echo htmlspecialchars($email);
Correct pattern: If you know the form uses POST, read from $_POST instead of $_REQUEST.

1.4 PHP Form Data and Security

The guide warns that submitted values can include malicious HTML or JavaScript. Printing raw input can cause cross-site scripting. Escape output with htmlspecialchars() and validate values before using them.

$safeName = htmlspecialchars($_POST["firstName"]);

if (filter_var($_POST["emailAddress"], FILTER_VALIDATE_EMAIL)) {
	echo "Valid email";
} else {
	echo "Invalid email";
}
Never do this: Do not display a submitted password back to the page, and do not use raw request values in HTML output.

1.5 Handling Empty Form Fields

Some controls send an empty value when left blank, while others send no key at all. If the key does not exist, reading it directly can produce an undefined index notice.

Control If Empty or Unselected PHP Check
Text, password, hidden, textarea, file input Field name is sent with an empty value empty($_POST["field"])
Checkbox, radio, list box, multi-select Nothing may be sent isset($_POST["field"])
Reset and push buttons Nothing is sent Do not rely on them as submitted values
if (isset($_POST["gender"])) {
	echo htmlspecialchars($_POST["gender"]);
}

1.6 Dynamic Forms and Validation

The guide describes a PHP-generated form that checks missing required fields, highlights errors, keeps previous values, and shows a thank-you message only after successful validation.

  • processForm() checks submitted required fields.
  • displayForm($missingFields) redisplays the form with feedback.
  • setValue(), setChecked(), and setSelected() preserve user input.
  • validateField() marks missing fields for styling.
$missing = [];
foreach (["name", "email", "age"] as $field) {
	if (empty($_POST[$field])) {
		$missing[] = $field;
	}
}
Revision task: Practise validating name, email, and age, then extend the same idea to login forms, multi-select lists, and file uploads.
Topic 1 Extended Code Example: Widget Club Form Handler

This example follows the guide's registration.html and process_registration.php idea, but it applies the later security and empty-field rules so the revision version is safer than the first teaching example. It demonstrates form handling only; it does not create an account or store a password.

registration.html: save this form beside process_registration.php. Each control name matches a key used by the handler below.

<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Widget Club Registration</title>
</head>
<body>
	<h1>Join the Widget Club</h1>
	<form action="process_registration.php" method="post">
		<p>
			<label for="firstName">First name</label>
			<input id="firstName" name="firstName" type="text" required>
		</p>
		<p>
			<label for="lastName">Last name</label>
			<input id="lastName" name="lastName" type="text" required>
		</p>
		<p>
			<label for="password1">Password</label>
			<input id="password1" name="password1" type="password" required>
		</p>
		<p>
			<label for="password2">Confirm password</label>
			<input id="password2" name="password2" type="password" required>
		</p>
		<fieldset>
			<legend>Gender</legend>
			<label><input name="gender" type="radio" value="female" required> Female</label>
			<label><input name="gender" type="radio" value="male"> Male</label>
			<label><input name="gender" type="radio" value="other"> Prefer to self-describe</label>
		</fieldset>
		<p>
			<label for="favoriteWidget">Favorite widget</label>
			<select id="favoriteWidget" name="favoriteWidget">
				<option value="">Choose one (optional)</option>
				<option value="clockwork bird">Clockwork bird</option>
				<option value="pocket telescope">Pocket telescope</option>
				<option value="self-stirring mug">Self-stirring mug</option>
			</select>
		</p>
		<p>
			<label><input name="newsletter" type="checkbox" value="yes"> Send me the newsletter</label>
		</p>
		<p>
			<label for="comments">Comments (optional)</label>
			<textarea id="comments" name="comments" rows="4" cols="40"></textarea>
		</p>
		<button type="submit">Send registration</button>
	</form>
</body>
</html>

process_registration.php: read the submitted values, check required fields, then escape text before displaying it.

<?php
// process_registration.php
// This script receives the Widget Club form through method="post".
// Every key below must match a form control's name attribute.

$requiredFields = ["firstName", "lastName", "password1", "password2", "gender"];
$missingFields = [];

foreach ($requiredFields as $fieldName) {
	// empty() catches fields that exist but contain an empty string.
	// It is useful for required text and password fields.
	if (empty($_POST[$fieldName])) {
		$missingFields[] = $fieldName;
	}
}

// The newsletter checkbox is optional, so it may not exist in $_POST.
// isset() avoids an undefined index notice when the box was not ticked.
$newsletter = isset($_POST["newsletter"]) ? "yes" : "no";

// Escape output before displaying submitted text in HTML.
$firstName = htmlspecialchars($_POST["firstName"] ?? "");
$lastName = htmlspecialchars($_POST["lastName"] ?? "");
$favoriteWidget = htmlspecialchars($_POST["favoriteWidget"] ?? "");
$comments = htmlspecialchars($_POST["comments"] ?? "");

if ($missingFields) {
	echo "<h1>Please complete the required fields</h1>";
	echo "<p>Missing: " . htmlspecialchars(implode(", ", $missingFields)) . "</p>";
	exit;
}

if ($_POST["password1"] !== $_POST["password2"]) {
	echo "<p>The passwords do not match. Please try again.</p>";
	exit;
}

echo "<h1>Thank You</h1>";
echo "<dl>";
echo "<dt>First name</dt><dd>$firstName</dd>";
echo "<dt>Last name</dt><dd>$lastName</dd>";
echo "<dt>Gender</dt><dd>" . htmlspecialchars($_POST["gender"]) . "</dd>";
echo "<dt>Favorite widget</dt><dd>$favoriteWidget</dd>";
echo "<dt>Newsletter</dt><dd>$newsletter</dd>";
echo "<dt>Comments</dt><dd>$comments</dd>";
echo "</dl>";

// Exam trap: the guide's first handler printed the submitted password.
// A secure revision answer should never display password values back to the user.
?>
Topic 1 Extended Code Example: Study Session Form With Validation

This single-file example combines an HTML form with a PHP POST handler. It checks that the learner name is present and no longer than 40 characters, that the topic is one of the allowed choices, and that minutes is an integer from 5 to 180. Save it as study-log.php and run it through a PHP-enabled local server. The character-count check uses PHP's mbstring extension.

study-log.php: the handler runs before any HTML is sent, so validation and response output can be decided first.

<?php
// The allowed values are defined by the server, not trusted from the request.
$topics = ["HTML forms", "PHP validation", "Cookies and sessions"];
$form = ["learner" => "", "topic" => "", "minutes" => ""];
$errors = [];
$minutesValue = null;
$submitted = $_SERVER["REQUEST_METHOD"] === "POST";

if ($submitted) {
    // Ignore unexpected array input; normal form controls submit strings.
    foreach (["learner", "topic", "minutes"] as $field) {
        $value = $_POST[$field] ?? "";
        $form[$field] = is_string($value) ? trim($value) : "";
    }

    if ($form["learner"] === "") {
        $errors[] = "Your name is required.";
    } elseif (mb_strlen($form["learner"], "UTF-8") > 40) {
        $errors[] = "Your name must be 40 characters or fewer.";
    }

    if (!in_array($form["topic"], $topics, true)) {
        $errors[] = "Choose a valid study topic.";
    }

    $minutesValue = filter_var($form["minutes"], FILTER_VALIDATE_INT);
    if ($minutesValue === false || $minutesValue < 5 || $minutesValue > 180) {
        $errors[] = "Minutes must be a whole number from 5 through 180.";
    }
}

function escapeHtml(string $value): string {
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8");
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Study Session Log</title>
</head>
<body>
    <h1>Log a study session</h1>

    <?php if ($submitted && $errors): ?>
        <div role="alert">
            <h2>Please correct these items</h2>
            <ul>
                <?php foreach ($errors as $error): ?>
                    <li><?= escapeHtml($error) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php elseif ($submitted): ?>
        <p role="status">
            <?= escapeHtml($form["learner"]) ?> studied
            <?= escapeHtml($form["topic"]) ?> for <?= $minutesValue ?> minutes.
        </p>
    <?php endif; ?>

    <form action="study-log.php" method="post">
        <p>
            <label for="learner">Your name</label>
            <input id="learner" name="learner" type="text" maxlength="40" required
                   value="<?= escapeHtml($form["learner"]) ?>">
        </p>
        <p>
            <label for="topic">Study topic</label>
            <select id="topic" name="topic" required>
                <option value="">Choose a topic</option>
                <?php foreach ($topics as $topic): ?>
                    <option value="<?= escapeHtml($topic) ?>"<?= $form["topic"] === $topic ? " selected" : "" ?>><?= escapeHtml($topic) ?></option>
                <?php endforeach; ?>
            </select>
        </p>
        <p>
            <label for="minutes">Minutes (5–180)</label>
            <input id="minutes" name="minutes" type="number" min="5" max="180" step="1" required
                   value="<?= escapeHtml($form["minutes"]) ?>">
        </p>
        <button type="submit">Save study session</button>
    </form>
</body>
</html>
  • $_SERVER["REQUEST_METHOD"] selects the POST-processing path; the first page visit only displays the form.
  • $_POST[$field] ?? "" handles absent controls. The is_string() guard also avoids warnings if a request submits an array instead of a normal text value.
  • in_array(..., true) checks the submitted topic against the server-side allowlist using strict comparison.
  • filter_var(..., FILTER_VALIDATE_INT) rejects non-integers; the following comparisons enforce the permitted range.
  • HTML attributes and displayed text are escaped when output. Browser constraints such as required, maxlength, and min/max help users but do not replace server-side validation.

Review request superglobals · Review output security · Review form validation

Topic 1 Extended Code Example: Redisplay A Form With Validation

The guide's generated-form section names helpers such as processForm(), displayForm(), setValue(), setChecked(), setSelected(), and validateField(). This compact version shows how those functions fit together.

<?php
// Single-page PHP form: first display, failed redisplay, and success display.

$requiredFields = ["name", "email", "age", "gender"];

function safe($value) {
	return htmlspecialchars($value ?? "", ENT_QUOTES);
}

function setValue($fieldName) {
	// Keeps typed values when the form is redisplayed after an error.
	echo safe($_POST[$fieldName] ?? "");
}

function setChecked($fieldName, $fieldValue) {
	// Keeps radio buttons or checkboxes selected after redisplay.
	if (isset($_POST[$fieldName]) && $_POST[$fieldName] === $fieldValue) {
		echo " checked";
	}
}

function validateField($fieldName, $missingFields) {
	// Adds an error class to a label when the field is missing.
	echo in_array($fieldName, $missingFields, true) ? " class=\"error\"" : "";
}

function processForm($requiredFields) {
	$missingFields = [];

	foreach ($requiredFields as $fieldName) {
		if (empty($_POST[$fieldName])) {
			$missingFields[] = $fieldName;
		}
	}

	if (!empty($_POST["email"]) && !filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
		$missingFields[] = "email format";
	}

	if (!empty($_POST["age"]) && ($_POST["age"] < 18 || $_POST["age"] > 60)) {
		$missingFields[] = "age range";
	}

	return $missingFields;
}

$missingFields = $_SERVER["REQUEST_METHOD"] === "POST" ? processForm($requiredFields) : [];

if ($_SERVER["REQUEST_METHOD"] === "POST" && !$missingFields) {
	echo "<h1>Thanks, " . safe($_POST["name"]) . "</h1>";
	echo "<p>Your submitted details passed validation.</p>";
} else {
?>
<form action="<?= safe($_SERVER["PHP_SELF"]) ?>" method="post">
	<label<?php validateField("name", $missingFields); ?>>Name</label>
	<input type="text" name="name" value="<?php setValue("name"); ?>">

	<label<?php validateField("email", $missingFields); ?>>Email</label>
	<input type="email" name="email" value="<?php setValue("email"); ?>">

	<label<?php validateField("age", $missingFields); ?>>Age</label>
	<input type="number" name="age" min="18" max="60" value="<?php setValue("age"); ?>">

	<label><input type="radio" name="gender" value="F"<?php setChecked("gender", "F"); ?>> Female</label>
	<label><input type="radio" name="gender" value="M"<?php setChecked("gender", "M"); ?>> Male</label>

	<button type="submit">Submit</button>
</form>
<?php } ?>
Topic 1 Review Exercise: Process a Multi-Select List

Use name="languages[]" so PHP receives an array. Accept only known options, then escape each value before HTML output.

<?php
$allowed = ["PHP", "JavaScript", "Python"];
$selected = [];
if ($_SERVER["REQUEST_METHOD"] === "POST") {
	$raw = $_POST["languages"] ?? [];
	if (!is_array($raw)) $raw = [];
	$selected = array_values(array_intersect($allowed, $raw));
	echo "<p>Selected: " . htmlspecialchars(implode(", ", $selected), ENT_QUOTES, "UTF-8") . "</p>";
}
?>
<form method="post">
	<label for="languages">Favourite languages</label>
	<select id="languages" name="languages[]" multiple size="3">
		<?php foreach ($allowed as $language): ?>
			<option value="<?= htmlspecialchars($language, ENT_QUOTES, "UTF-8") ?>"<?= in_array($language, $selected, true) ? " selected" : "" ?>><?= htmlspecialchars($language, ENT_QUOTES, "UTF-8") ?></option>
		<?php endforeach; ?>
	</select>
	<button type="submit">Submit</button>
</form>
Topic 1 Review Exercise: Validate and Display an Image Upload

This matches the review requirements: JPG/JPEG/PNG only, at most 2 MB, saved in uploads/, with an error if a check fails. The image content is checked as well as the filename extension. Save as upload.php and ensure the web server can write to the project folder.

<?php
$message = "";
$imageUrl = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
	$file = $_FILES["photo"] ?? null;
	if (!$file || $file["error"] !== UPLOAD_ERR_OK) {
		$message = "Choose an image and try again.";
	} elseif ($file["size"] > 2 * 1024 * 1024) {
		$message = "The image must be 2 MB or smaller.";
	} else {
		$extension = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));
		$type = (new finfo(FILEINFO_MIME_TYPE))->file($file["tmp_name"]);
		$allowed = ["jpg" => "image/jpeg", "jpeg" => "image/jpeg", "png" => "image/png"];
		if (!isset($allowed[$extension]) || $allowed[$extension] !== $type || getimagesize($file["tmp_name"]) === false) {
			$message = "Only JPG, JPEG, and PNG images are allowed.";
		} else {
			$folder = __DIR__ . "/uploads";
			if (!is_dir($folder) && !mkdir($folder, 0755)) {
				$message = "Could not create the uploads folder.";
			} else {
				$name = bin2hex(random_bytes(16)) . "." . $extension;
				if (move_uploaded_file($file["tmp_name"], $folder . "/" . $name)) {
					$imageUrl = "uploads/" . $name;
				} else {
					$message = "Could not save the uploaded image.";
				}
			}
		}
	}
}
?>
<form method="post" enctype="multipart/form-data">
	<label for="photo">Image (JPG or PNG, up to 2 MB)</label>
	<input id="photo" name="photo" type="file" accept=".jpg,.jpeg,.png" required>
	<button type="submit">Upload</button>
</form>
<?php if ($message !== ""): ?><p><?= htmlspecialchars($message, ENT_QUOTES, "UTF-8") ?></p><?php endif; ?>
<?php if ($imageUrl !== ""): ?><img src="<?= htmlspecialchars($imageUrl, ENT_QUOTES, "UTF-8") ?>" alt="Uploaded image"><?php endif; ?>
Topic 1 Review Exercise: Password Hash and Prepared Login Query

The review requires a prepared statement, password hashing, and safe output. Assume a users table with username and password_hash columns, a working $conn MySQLi connection, and HTTPS. Save the hash at registration; never save the original password.

<?php
// During registration, after validating the submitted password:
$hash = password_hash($password, PASSWORD_DEFAULT);
$insert = mysqli_prepare($conn, "INSERT INTO users (username, password_hash) VALUES (?, ?)");
mysqli_stmt_bind_param($insert, "ss", $username, $hash);
mysqli_stmt_execute($insert);
mysqli_stmt_close($insert);

// During login, retrieve the stored hash with a parameterized query:
$username = trim($_POST["username"] ?? "");
$password = $_POST["password"] ?? "";
$query = mysqli_prepare($conn, "SELECT password_hash FROM users WHERE username = ?");
mysqli_stmt_bind_param($query, "s", $username);
mysqli_stmt_execute($query);
mysqli_stmt_bind_result($query, $storedHash);
$found = mysqli_stmt_fetch($query);
mysqli_stmt_close($query);
if ($found && password_verify($password, $storedHash)) {
	session_start();
	session_regenerate_id(true);
	$_SESSION["username"] = $username;
	echo "Welcome, " . htmlspecialchars($username, ENT_QUOTES, "UTF-8");
} else {
	echo "Invalid username or password.";
}

Check connection and statement errors in a real application. The form uses method="post" and password input type="password"; output escaping protects the greeting, while the prepared query protects SQL parameters.

Topic 1 Glossary: Forms, Request Data And Validation
<form>
The HTML element that groups form controls and defines how submitted data is sent.
action
The form attribute that names the page or script that receives the submitted data.
method
The form attribute that chooses the HTTP submission method, usually get or post.
GET
A request method that sends field names and values in the URL query string.
POST
A request method that sends form data in the request body and supports larger submissions.
name
The form-control attribute PHP uses as the key in $_GET or $_POST.
value
The submitted value paired with a form control's name.
$_GET
The PHP superglobal array containing values submitted with the GET method.
$_POST
The PHP superglobal array containing values submitted with the POST method.
$_REQUEST
A combined request array that can include $_GET, $_POST, and $_COOKIE; useful but less precise.
superglobal
A built-in PHP variable available in any scope, including inside functions.
htmlspecialchars()
Converts special HTML characters to entities so submitted text is safer to display.
filter_var()
A PHP validation/filtering function used in the guide with FILTER_VALIDATE_EMAIL.
isset()
Checks whether a submitted key exists before the script reads it.
empty()
Checks whether a submitted value is absent, blank, or otherwise empty.
array_key_exists()
Alternative key-existence check mentioned for avoiding undefined index notices.
Undefined index
A PHP notice caused by trying to read a field that was not submitted.
XSS
Cross-site scripting; a risk when user-submitted HTML or JavaScript is displayed as executable page content.
setValue()
A helper pattern that repopulates a text field after validation fails.
setChecked()
A helper pattern that keeps a checkbox or radio option selected after form redisplay.
setSelected()
A helper pattern that keeps the correct <option> selected in a dropdown.
validateField()
A helper pattern that marks missing fields with an error style.
password_hash()
Review-question function for storing passwords as hashes instead of plain text.
password_verify()
Review-question function for checking a typed password against a stored hash.
prepared statements
Review-question security technique for reducing SQL injection risk in login code.
$_FILES
The PHP superglobal used for uploaded file information in the file-upload exercise.
move_uploaded_file()
The PHP function used to move an uploaded file into a chosen folder such as uploads/.
Back to Topics 1 & 2 Test Index

Topic 2: Session Controls and Cookies

This topic explains how PHP remembers information between requests. The key idea is state: HTTP forgets, while query strings, cookies, and sessions help applications remember.

stateless HTTP query strings setcookie() PHPSESSID session_start() logout flow

2.1 Stateless HTTP

Each browser request is independent. Ordinary request-local PHP variables do not automatically carry into the next request. Applications such as shopping carts, login systems, forums, and multi-page forms need a state mechanism to connect related requests.

Query string Cookie Session ID Server state
Core idea: State means the application can connect a later request to earlier activity from the same user.

2.2 Cookies

A cookie is a small piece of data sent by the server and stored by the browser. On later requests, the browser sends it back, letting PHP identify preferences or repeat visits.

setcookie("bg", "#000000", time() + 60 * 60 * 2);

if (isset($_COOKIE["bg"])) {
	echo htmlspecialchars($_COOKIE["bg"]);
}
  • name identifies the cookie.
  • value stores the data.
  • expire controls lifetime.
  • path, domain, and secure control where and how it is sent.
Headers first: Call setcookie() before any HTML output.

2.3 Sessions

Sessions store associated data on the server and link requests through a session ID. PHP commonly sends that ID in a browser cookie called PHPSESSID. Session lifetime depends on server configuration and application behavior; do not assume a session always lasts across visits.

session_start();

$_SESSION["hits"] = ($_SESSION["hits"] ?? 0) + 1;
echo "This page has been viewed " . $_SESSION["hits"] . " times.";
  • session_start() loads or creates the session.
  • $_SESSION holds session values.
  • session_id() gets the current session ID.
  • session_destroy() destroys session data.

2.5 Combining Cookies and Sessions

The guide explains that temporary state can live in a PHP session, while a non-sensitive preference can be stored in a cookie and used across visits. A cookie value is user-controlled: validate it before using it, and do not store passwords or secrets there.

if (isset($_POST["bgcolor"])) {
	setcookie("bgcolor", $_POST["bgcolor"], time() + 60 * 60 * 24 * 7);
}

$background = $_COOKIE["bgcolor"] ?? $_POST["bgcolor"] ?? "gray";
Applied pattern: A login system can store the current username in $_SESSION, while a preference cookie remembers a color choice for the next visit.

2.6 Review Tasks

  • Create a hardcoded login using sessions, a welcome page, and logout.
  • Set, read, display, and delete a user_preference cookie.
  • Create a three-step registration form that preserves values with sessions and destroys the session after final submission.
Topic 2 Extended Code Example: Session Login, Welcome And Logout

The study guide review task asks for a hardcoded login, a welcome page, and logout. This simplified exercise demonstrates the session flow only; hardcoded credentials are not suitable for a real login system. The supporting logout clears session data and expires the session cookie.

<?php
// login.php
session_start();

$validUsername = "student";
$validPassword = "richfield";
$error = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
	if ($_POST["username"] === $validUsername && $_POST["password"] === $validPassword) {
		// Session data is stored on the server and linked to the browser by PHPSESSID.
		$_SESSION["username"] = $_POST["username"];
		header("Location: welcome.php");
		exit;
	}

	$error = "Invalid username or password.";
}
?>
<form action="login.php" method="post">
	<p><?= htmlspecialchars($error) ?></p>
	<input type="text" name="username" placeholder="Username">
	<input type="password" name="password" placeholder="Password">
	<button type="submit">Log in</button>
</form>

<?php
// welcome.php
session_start();

if (!isset($_SESSION["username"])) {
	header("Location: login.php");
	exit;
}

echo "<h1>Welcome, " . htmlspecialchars($_SESSION["username"]) . "</h1>";
echo "<p><a href=\"logout.php\">Log out</a></p>";

// logout.php
session_start();
$_SESSION = [];
session_destroy();
if (ini_get("session.use_cookies")) {
	$params = session_get_cookie_params();
	setcookie(session_name(), "", time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
}
header("Location: login.php");
exit;
?>
Topic 2 Glossary: State, Cookies And Sessions
state
Stored information that connects one browser request to another.
stateless protocol
A protocol where each request is independent; the guide identifies HTTP this way.
query string
Small state data placed in the URL after the question mark.
cookie
A small string of data sent by the server, stored by the browser, and returned on later requests.
setcookie()
The PHP function that sends a cookie header to the browser.
$_COOKIE
The PHP superglobal containing cookies sent back by the browser.
expire
The cookie parameter that controls when a cookie should stop being stored.
time()
Returns the current UNIX timestamp; used in cookie expiry calculations such as time() + 60 * 60 * 2.
path
The cookie parameter that limits which URLs on the server receive the cookie.
domain
The cookie parameter that limits which hostnames receive the cookie.
secure
The cookie parameter that tells the browser to send the cookie only over HTTPS.
Cookie size
Cookies are small; about 4 KB is a common practical approximation, while actual limits vary by browser and cookie rules.
session
Server-side persistent variables linked to a user's browser by a session ID.
session_start()
Begins or resumes a PHP session and loads values into $_SESSION.
$_SESSION
The PHP superglobal array used to store session variables.
session_id()
Returns the current session identifier.
session_destroy()
Destroys the session data store; useful during logout or after final form submission.
PHPSESSID
The default cookie name PHP commonly uses to carry the session ID.
--enable-trans-id
The PHP compile option mentioned for automatically rewriting links with session IDs.
URL session ID
An alternative to cookie-based session IDs, but it can expose the ID in links and logs.
user_preference
The review-question cookie name used to store a user's favourite colour.
header()
A PHP function often used in login examples to redirect after state changes.
Back to Topics 1 & 2 Test Index

Topic 3: File System Management

PHP can work with files and directories on the server. This topic covers file metadata, paths, open modes, reading, writing, pointer movement, copying, deleting, directory traversal, and file-type checks.

file metadata fopen modes file handles EOF and pointers directory handles CSV and counters

3.1 Files, Directories, and Metadata

A file is an ordered sequence of bytes. A directory is a special file that stores file and subdirectory names plus pointers to their locations. PHP provides functions to inspect both.

file_exists()
Checks whether a path exists.
filesize()
Returns size in bytes.
fileatime()
Last access timestamp.
filectime()
Last change timestamp.
filemtime()
Last modification timestamp.
basename()
Extracts the filename from a path.
if (file_exists("example.txt")) {
	echo filesize("example.txt");
	echo date("Y-m-d", filemtime("example.txt"));
}

3.2 Opening Files With fopen()

fopen() returns a file handle used by later read, write, and close functions. The mode matters because some modes erase existing content.

Mode Meaning Main Risk
r Read only; file must exist Fails if missing
w Write only; creates file or erases existing file Destroys old content
a Append only; writes at the end Cannot read without another mode
r+, w+, a+ Read/write variants w+ also erases old content
Portability note: The guide recommends binary mode such as rb when you want to avoid operating-system line-ending conversions.

3.3 Reading and Writing

Use the function that matches the job: whole-file reads for small files, line-by-line reads for logs or CSV data, and pointer-based reads when you need exact positions.

fread()
Reads a specified number of bytes or characters.
fgetc()
Reads one character at a time.
fgets()
Reads one line at a time.
fgetcsv()
Reads CSV rows into arrays.
file()
Reads a file into an array of lines.
file_get_contents()
Reads the whole file into a string.
fwrite()
Writes through an open handle.
file_put_contents()
Writes a full string without manually opening a handle.
readfile()
Reads a file and sends it to output.
fpassthru()
Sends the remaining bytes from an open file handle to output.
$handle = fopen("data.txt", "a");
if ($handle) {
	fwrite($handle, "New line" . PHP_EOL);
	fclose($handle);
}

3.4 EOF and Random Access

PHP maintains an internal pointer for open files. Some functions move it forward as they read. You can also move it manually.

  • feof() checks whether the end of the file has been reached.
  • fseek() moves the pointer to a specific offset.
  • ftell() returns the current pointer position.
  • rewind() moves the pointer back to the start.
$handle = fopen("hello_world.txt", "r");
fseek($handle, 7);
echo fread($handle, 5); // world
fclose($handle);

3.5 Working With Directories

Directory handles work like file handles. Open the directory, read each entry, skip . and .., then close the handle.

$handle = opendir("files_dir");
if ($handle) {
	while (($file = readdir($handle)) !== false) {
		if ($file !== "." && $file !== "..") {
			echo htmlspecialchars($file) . "<br>";
		}
	}
	closedir($handle);
}
opendir()
Opens a directory handle.
readdir()
Reads the next entry.
closedir()
Closes the directory handle.
rewinddir()
Moves the pointer back to the first entry.
chdir()
Changes the current working directory.
getcwd()
Returns the current working directory.
mkdir()
Creates a directory.
rmdir()
Removes an empty directory.
dirname()
Returns the directory portion of a path.

3.6 Copy, Rename, Delete, and Test Types

File management functions can change data permanently, so check paths before using them.

  • copy($source, $destination) copies a file.
  • rename($old, $new) renames or moves a file.
  • unlink($path) deletes a file.
  • is_dir($path) checks for directories.
  • is_file($path) checks for regular files.
if (file_exists("report.txt")) {
	copy("report.txt", "report_backup.txt");
}
Destructive action: unlink() deletes the file. Make sure the target path is correct before calling it.

3.7 The Directory Object

The guide also shows an object-oriented way to list a directory. dir() returns a Directory object with path and handle properties. Its read(), rewind(), and close() methods correspond to readdir(), rewinddir(), and closedir().

$dir = dir(__DIR__ . "/files_dir");
if ($dir !== false) {
	while (($name = $dir->read()) !== false) {
		if ($name === "." || $name === "..") continue;
		echo htmlspecialchars($name, ENT_QUOTES, "UTF-8") . "<br>";
	}
	$dir->close();
}

Use !== false so a directory entry named 0 is not mistaken for the end. Check that dir() succeeded before calling a method.

Topic 3 Extended Code Example: Metadata Check And Hit Counter

This combines the guide's practical tasks for example.txt and the hit-counter example using count.dat. Notice how the script checks existence before reading and closes each file handle after use.

<?php
// file_status_and_counter.php
// Demonstrates file_exists(), filesize(), filemtime(), fopen(), fread(), fwrite(), and fclose().

$exampleFile = "example.txt";

if (file_exists($exampleFile)) {
	echo "<p>File size: " . filesize($exampleFile) . " bytes</p>";
	echo "<p>Last modified: " . date("Y-m-d H:i:s", filemtime($exampleFile)) . "</p>";
} else {
	// file_put_contents() creates or overwrites the whole file in one call.
	file_put_contents($exampleFile, "Hello, this is a new file!");
	echo "<p>example.txt was created.</p>";
}

$counterFile = "counter.txt";

if (!file_exists($counterFile)) {
	// Create the counter file with an initial zero.
	file_put_contents($counterFile, "0", LOCK_EX);
}

$handle = fopen($counterFile, "r");
if (!$handle) {
	die("Cannot read the counter file.");
}

// Read up to 20 characters and cast the result to an integer.
$counter = (int) fread($handle, 20);
fclose($handle);

$counter++;

$handle = fopen($counterFile, "w");
if (!$handle) {
	die("Cannot open the counter file for writing.");
}

// Opening with "w" erases old content, then writes the new visit count.
fwrite($handle, (string) $counter);
fclose($handle);

echo "<p>You are visitor #$counter.</p>";
?>
Topic 3 Extended Code Example: Directory Listing And CSV Table

The guide treats directories like file-like structures with handles, then asks for a CSV table in the review. This example shows both: create/list files_dir, skip . and .., then read CSV rows with fgetcsv().

<?php
// directory_and_csv.php

$dirPath = "files_dir";

if (!is_dir($dirPath)) {
	mkdir($dirPath);
	file_put_contents($dirPath . "/file1.txt", "First sample file");
	file_put_contents($dirPath . "/file2.txt", "Second sample file");
}

$handle = opendir($dirPath);
if (!$handle) {
	die("Cannot open the directory.");
}

echo "<h2>Directory contents</h2><ul>";
$foundEntries = false;

while (($entry = readdir($handle)) !== false) {
	if ($entry === "." || $entry === "..") {
		continue;
	}

	$foundEntries = true;
	$fullPath = $dirPath . "/" . $entry;
	$type = is_dir($fullPath) ? "directory" : (is_file($fullPath) ? "file" : "other");

	echo "<li>" . htmlspecialchars($entry) . " (" . $type . ")</li>";
}

closedir($handle);
echo $foundEntries ? "</ul>" : "<li>Directory is empty</li></ul>";

$csvFile = "data.csv";

if (!file_exists($csvFile)) {
	file_put_contents($csvFile, "name,age,city\nAsha,20,Durban\nChris,24,Cape Town\n");
}

$csvHandle = fopen($csvFile, "r");
if (!$csvHandle) {
	die("Cannot open CSV file.");
}

echo "<h2>CSV data</h2><table>";

while (($row = fgetcsv($csvHandle)) !== false) {
	echo "<tr>";
	foreach ($row as $cell) {
		echo "<td>" . htmlspecialchars($cell) . "</td>";
	}
	echo "</tr>";
}

echo "</table>";
fclose($csvHandle);
?>
Topic 3 Review Exercises: Read, Append, Handle Errors, and Copy Binary Data

This completes the file review tasks alongside the metadata, counter, directory, and CSV examples above. The first script creates data.txt, reads it line by line, appends a sentence, and reports a missing file clearly.

<?php
$path = __DIR__ . "/data.txt";
if (!file_exists($path) && file_put_contents($path, "Initial data\n") === false) {
	die("Cannot create data.txt.");
}
$reader = fopen($path, "r");
if ($reader === false) die("Cannot open data.txt for reading.");
while (($line = fgets($reader)) !== false) {
	echo htmlspecialchars($line, ENT_QUOTES, "UTF-8") . "<br>";
}
fclose($reader);
if (file_put_contents($path, "This is new data added.\n", FILE_APPEND | LOCK_EX) === false) {
	die("Cannot append to data.txt.");
}
$missing = @fopen(__DIR__ . "/nonexistent.txt", "r");
if ($missing === false) echo "The requested file could not be opened.";
else fclose($missing);

For the binary task, use rb/wb, count bytes with strlen(), and never echo raw binary into an HTML page. Supply a small sample.png file first.

<?php
$source = fopen(__DIR__ . "/sample.png", "rb");
if ($source === false) die("Cannot read sample.png.");
$bytes = stream_get_contents($source);
fclose($source);
if ($bytes === false) die("Cannot read binary data.");
echo "Read " . strlen($bytes) . " bytes.";
$target = fopen(__DIR__ . "/sample-copy.png", "wb");
if ($target === false) die("Cannot create the copy.");
$written = fwrite($target, $bytes);
fclose($target);
if ($written !== strlen($bytes)) die("The binary copy was incomplete.");
Topic 3 Glossary: Files, Pointers And Directories
file
An ordered sequence of stored data; the guide focuses mainly on text files.
directory
A special file that stores entries for files and subdirectories; also called a folder.
file_exists()
Returns true when a path exists and false otherwise.
filesize()
Returns the size of a file in bytes, or false if an error occurs.
fileatime()
Returns the last access time of a file as a UNIX timestamp.
filectime()
Returns the last changed time of a file, including creation, write, or permission changes.
filemtime()
Returns the last modified time of a file's contents.
UNIX timestamp
An integer count of seconds since midnight on January 1, 1970.
basename()
Returns the final filename or directory segment from a path; can remove a suffix.
dirname()
Returns the directory part of a full path.
fopen()
Opens a file and returns a file handle used for reading, writing, or closing.
file handle
A pointer-like value representing an open file.
r
fopen() mode for reading an existing file from the beginning.
w
fopen() mode for writing; creates a file or erases existing content.
a
fopen() mode for appending new data at the end of a file.
b
Binary mode suffix that avoids operating-system line-ending conversions.
fread()
Reads a specified number of characters or bytes from an open file.
fgetc()
Reads one character at a time; useful but slow for large files.
fgets()
Reads one line from the current file pointer.
fgetcsv()
Reads one CSV row and returns its values as an array.
fwrite()
Writes a string through an open file handle and returns the number of characters written.
feof()
Returns true after the script has tried to read past the end of a file.
file()
Reads a whole file into an array of lines.
file_get_contents()
Reads a whole file into one string; best for smaller files.
file_put_contents()
Writes a whole string to a file without manually opening a handle.
FILE_APPEND
Flag that appends instead of overwriting in file_put_contents().
LOCK_EX
Flag that locks the file during writing to reduce simultaneous write conflicts.
fpassthru()
Outputs the remaining contents of an open file directly to the browser.
readfile()
Outputs a file directly without needing a manual fopen().
fseek()
Moves the file pointer to a new position.
SEEK_SET
Positions a file pointer relative to the start of the file.
SEEK_CUR
Positions a file pointer relative to the current pointer location.
SEEK_END
Positions a file pointer relative to the end of the file.
ftell()
Returns the current file pointer position.
rewind()
Moves the file pointer back to the beginning.
copy()
Copies a file from one path to another.
rename()
Renames or moves a file.
unlink()
Deletes a file from the server.
opendir()
Opens a directory and returns a directory handle.
readdir()
Reads the next entry in a directory handle.
closedir()
Closes a directory handle.
rewinddir()
Resets a directory handle to its first entry.
chdir()
Changes PHP's current working directory.
getcwd()
Returns PHP's current working directory.
mkdir()
Creates a directory.
rmdir()
Deletes an empty directory.
dir()
Creates a Directory object with read(), rewind(), and close() methods.
is_dir()
Checks whether a path is a directory.
is_file()
Checks whether a path is a regular file.
Back to Exam Focus Areas

Topic 4: Databases and Structured Query Language

This topic moves from file storage limitations to relational databases, SQL statements, and PHP-to-MySQL connection code.

RDBMS embedded vs client-server fruit table CRUD SQL WHERE clause mysqli

4.1 Database Architecture and RDBMS Concepts

An embedded database runs inside the application and is usually local to one machine. A client-server database can serve multiple applications over a network and centralize administration and backups.

Concept Meaning
Table Structured storage made of rows and columns.
Row / record One complete set of related values.
Column / field One data attribute with the same meaning for every row.
Primary key A unique identifier for each record.
Index A sorted structure that speeds lookup but slows some writes.

4.2 Creating Databases and Tables

Use MySQL commands to create a database, select it, and define tables. End each SQL statement with a semicolon.

CREATE DATABASE mydatabase;
USE mydatabase;

CREATE TABLE fruit (
	id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
	name VARCHAR(30) NOT NULL,
	color VARCHAR(30) NOT NULL,
	PRIMARY KEY (id)
);
Key detail: AUTO_INCREMENT lets MySQL generate the primary key value automatically.

4.3 CRUD SQL

CRUD means create, read, update, and delete. In this guide, the fruit table is used to demonstrate the core SQL statements.

INSERT INTO fruit (name, color) VALUES ('banana', 'yellow');

SELECT * FROM fruit;
SELECT name, color FROM fruit WHERE id >= 2;

UPDATE fruit
SET name = 'grapefruit', color = 'yellow'
WHERE id = 2;

DELETE FROM fruit WHERE id = 2;
High-risk statements: DELETE FROM fruit; removes all rows. DROP TABLE fruit; removes the table itself.

4.4 Connecting PHP to MySQL

The guide explains mysqli and PDO, then shows procedural mysqli connection and query examples. Always check the connection and query result before processing rows.

$conn = mysqli_connect("localhost", "root", "", "mydatabase");

if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}

$result = mysqli_query($conn, "SELECT * FROM fruit");
if (!$result) {
	die("Query failed: " . mysqli_error($conn));
}

while ($row = mysqli_fetch_assoc($result)) {
	echo "<li>A " . htmlspecialchars($row["name"]) .
		" is " . htmlspecialchars($row["color"]) . "</li>";
}

mysqli_close($conn);

4.5 Review Query Patterns

The review work asks you to use an e-commerce schema with Customers and Orders. Practise joins, aggregation, table alteration, and deletion order.

SELECT c.Name, o.OrderID, o.TotalAmount
FROM Customers c
INNER JOIN Orders o ON c.CustomerID = o.CustomerID;

SELECT c.Name, SUM(o.TotalAmount) AS TotalSpent
FROM Customers c
INNER JOIN Orders o ON c.CustomerID = o.CustomerID
GROUP BY c.CustomerID, c.Name;
Foreign-key thinking: Delete dependent orders before deleting the customer they reference.

4.6 SQL Vocabulary

SELECT
Retrieves rows and returns a result set.
INSERT
Adds rows to a table.
UPDATE
Modifies existing rows.
DELETE
Deletes rows but leaves the table.
CREATE
Creates databases, tables, or indexes.
ALTER
Changes table structure.
DROP
Deletes a database or table structure.
WHERE
Filters affected or returned rows.
Topic 4 Extended Code Example: Build And Query The Fruit Database

This complete SQL script follows the guide's mydatabase and fruit example. It shows the exam sequence: create the database, select it, create a table, insert rows, read rows, update one row, delete one row, and verify the result.

-- Run these statements at the mysql > prompt after logging in with:
-- mysql -u root -p

CREATE DATABASE mydatabase;
USE mydatabase;

-- The id column is the primary key.
-- AUTO_INCREMENT lets MySQL generate id values automatically.
CREATE TABLE fruit (
	id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
	name VARCHAR(30) NOT NULL,
	color VARCHAR(30) NOT NULL,
	PRIMARY KEY (id),
	KEY (name)
);

-- Because id is AUTO_INCREMENT, only name and color are supplied.
INSERT INTO fruit (name, color) VALUES ('banana', 'yellow');
INSERT INTO fruit (name, color) VALUES ('tangerine', 'orange');
INSERT INTO fruit (name, color) VALUES ('plum', 'purple');

-- SELECT * retrieves every column from every row.
SELECT * FROM fruit;

-- Selecting named columns is clearer when you do not need the whole row.
SELECT name, color FROM fruit;

-- WHERE filters the rows returned by the query.
SELECT * FROM fruit WHERE name = 'banana';
SELECT * FROM fruit WHERE id >= 2;

-- Exam trap: always use WHERE when only one row should change.
UPDATE fruit
SET name = 'grapefruit', color = 'yellow'
WHERE id = 2;

-- DELETE removes rows but leaves the table structure in place.
DELETE FROM fruit WHERE id = 2;

-- DROP TABLE removes the whole table and all its data permanently.
-- DROP TABLE fruit;
Topic 4 Extended Code Example: Read Fruit Data From PHP

This follows the guide's get_fruit.php pattern. The PHP script connects with procedural mysqli, checks the connection, runs SELECT * FROM fruit, checks the query result, escapes output, and closes the connection.

<?php
// get_fruit.php
// Assumes mydatabase and fruit were already created in MySQL.

$servername = "localhost";
$username = "root";
$password = "";
$database = "mydatabase";

// Create the connection to the MySQL server and selected database.
$conn = mysqli_connect($servername, $username, $password, $database);

// Connection errors should stop the script because queries cannot work without a connection.
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT * FROM fruit";
$result = mysqli_query($conn, $sql);

// Query errors are different from connection errors.
// mysqli_error($conn) reports what went wrong with the SQL query.
if (!$result) {
	die("Query failed: " . mysqli_error($conn));
}

echo "<h1>Fruit</h1>";
echo "<ul>";

while ($row = mysqli_fetch_assoc($result)) {
	// The guide escapes name and color before putting them into HTML output.
	echo "<li>A "
		. htmlspecialchars($row["name"])
		. " is "
		. htmlspecialchars($row["color"])
		. "</li>";
}

echo "</ul>";

mysqli_close($conn);
?>

Topic 4 Exam-Style SQL Example: Customers And Orders

The review questions introduce Customers and Orders. Use this as a compact worked answer for joins, grouping, table alteration, and delete order.

CREATE TABLE Customers (
	CustomerID INT PRIMARY KEY AUTO_INCREMENT,
	Name VARCHAR(100),
	Email VARCHAR(100) UNIQUE,
	Country VARCHAR(50)
);

CREATE TABLE Orders (
	OrderID INT PRIMARY KEY AUTO_INCREMENT,
	CustomerID INT,
	OrderDate DATE,
	TotalAmount DECIMAL(10,2),
	FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);

-- Customers who have placed at least one order.
SELECT DISTINCT c.*
FROM Customers c
INNER JOIN Orders o ON c.CustomerID = o.CustomerID;

-- Orders with the customer's name.
SELECT o.OrderID, o.OrderDate, o.TotalAmount, c.Name
FROM Orders o
INNER JOIN Customers c ON o.CustomerID = c.CustomerID;

-- Total amount spent by each customer.
SELECT c.CustomerID, c.Name, SUM(o.TotalAmount) AS TotalSpent
FROM Customers c
INNER JOIN Orders o ON c.CustomerID = o.CustomerID
GROUP BY c.CustomerID, c.Name;

-- Manipulating the Customers table.
ALTER TABLE Customers ADD PhoneNumber VARCHAR(15);
ALTER TABLE Customers MODIFY Country VARCHAR(100);

-- Insert, update, and delete John Doe.
INSERT INTO Customers (Name, Email, Country)
VALUES ('John Doe', 'johndoe@example.com', 'USA');

UPDATE Customers
SET Email = 'john.doe@newmail.com'
WHERE Name = 'John Doe';

-- Delete dependent orders before deleting the referenced customer.
DELETE FROM Orders
WHERE CustomerID = (SELECT CustomerID FROM Customers WHERE Name = 'John Doe');

DELETE FROM Customers
WHERE Name = 'John Doe';
Topic 4 Glossary: Databases, SQL And MySQL From PHP
database
Structured storage designed to organize, search, filter, update, and manage large amounts of data efficiently.
embedded database
A database engine that runs inside the application and stores data on the same machine.
client-server database
A database architecture where a database server responds to client applications, often over a network.
database model
The way data is stored, organized, and accessed.
simple database
A key-based database model similar to an associative array, with no relationships between items.
relational database
A database that organizes data in tables and connects related data through common attributes.
RDBMS
Relational Database Management System; examples in the guide include Oracle, DB2, SQL Server, and MySQL.
table
A relational structure made of rows and columns.
row
One record in a table.
record
A complete set of related values in one row.
column
A field with the same meaning for every record in a table.
field
A named item of data such as name, color, or Email.
primary key
A unique identifier for each row, such as id or CustomerID.
index
A separate sorted list of column values that can make searches faster.
KEY
MySQL keyword for creating an index, used in the guide as KEY (name).
SQL
Structured Query Language, used to create, read, update, and delete database data and structures.
query
An SQL operation, especially one that retrieves records.
SELECT
Retrieves rows from one or more tables.
*
Wildcard in SELECT * meaning all columns.
FROM
The clause that names the table used by a query.
WHERE
The clause that filters rows returned, updated, or deleted.
INSERT
Adds a new row to a table.
REPLACE
Replaces a row when the same record already exists.
UPDATE
Changes existing row values; dangerous without WHERE.
DELETE
Removes rows from a table while leaving the table structure intact.
CREATE DATABASE
Creates a new MySQL database such as mydatabase.
CREATE TABLE
Creates a table and defines its fields, data types, keys, and constraints.
ALTER TABLE
Changes the structure of an existing table.
DROP TABLE
Permanently removes a table and all data inside it.
DROP DATABASE
Permanently removes a database and all its tables.
AUTO_INCREMENT
MySQL property that automatically generates the next numeric value for a key field.
NOT NULL
Constraint that prevents a field from being left empty at database level.
UNIQUE
Constraint that prevents duplicate values in a field such as Email.
FOREIGN KEY
A field that references a key in another table, such as Orders.CustomerID referencing Customers.CustomerID.
INNER JOIN
Combines matching rows from related tables.
GROUP BY
Groups rows for aggregate calculations such as total spending per customer.
SUM()
SQL aggregate function used to add numeric values such as TotalAmount.
mysqli
PHP's MySQL improved extension, available in procedural and object-oriented styles.
PDO
A PHP database option mentioned as another way to connect to databases.
mysqli_connect()
Creates a procedural MySQL connection from PHP.
mysqli_connect_error()
Returns the connection error message when mysqli_connect() fails.
mysqli_query()
Sends an SQL statement to MySQL through an open connection.
mysqli_error()
Returns the latest MySQL query error for a connection.
mysqli_fetch_assoc()
Fetches a result row as an associative array keyed by column name.
mysqli_close()
Closes an open MySQL connection.
Back to Exam Focus Areas

Addendum: Installing and Running PHP With XAMPP

The addendum explains XAMPP as the local development package used to run PHP and MySQL on your computer before publishing a site.

Apache MySQL PHP htdocs localhost .php files

5.1 What XAMPP Provides

XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It gives you a local web server and database setup for development and testing.

  • Apache serves web pages locally.
  • MySQL stores relational database data.
  • PHP executes server-side scripts.
  • htdocs is the folder where local projects are usually placed.

5.2 Run PHP

Create a folder inside htdocs, open that folder in your editor, save files with a .php extension, start Apache in XAMPP, then access the page through the browser.

<?php
echo "<h1>My Name is Derek</h1>";
?>
Syntax check: Make sure HTML tags are closed correctly inside echoed strings.

5.3 Localhost Path

If your folder is named Demo and your file is test.php, open it as:

http://localhost/Demo/test.php
Correct pattern: PHP must be served by Apache or another PHP-capable server. Opening a PHP file directly from Finder or File Explorer will not execute the PHP code.
Addendum Extended Code Example: First Local PHP Test Page

This example cleans up the addendum's first test.php idea. Save it inside your XAMPP project folder, start Apache, then open it through localhost.

<?php
// htdocs/Demo/test.php
// The file extension must be .php so Apache sends the page through PHP.

$studentName = "Derek";
$today = date("Y-m-d");
?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>PHP Test Page</title>
</head>
<body>
	<h1>My Name is <?= htmlspecialchars($studentName) ?></h1>
	<p>This page was processed by PHP on <?= htmlspecialchars($today) ?>.</p>
	<p>If you can see today's date, Apache and PHP are working through XAMPP.</p>
</body>
</html>
Addendum Extended Code Example: XAMPP Run Checks

Use this as a short troubleshooting script when a practical example behaves oddly. It reinforces the addendum's main rule: PHP should be run through the local server, not opened directly as a file.

<?php
// diagnostics.php
// Place this in htdocs/Demo and open http://localhost/Demo/diagnostics.php

echo "<h1>XAMPP Diagnostics</h1>";

// Shows which PHP version Apache is using.
echo "<p>PHP version: " . htmlspecialchars(PHP_VERSION) . "</p>";

// Confirms the server-side folder PHP is running from.
echo "<p>Current folder: " . htmlspecialchars(getcwd()) . "</p>";

// Checks whether the request really came through localhost.
echo "<p>Server name: " . htmlspecialchars($_SERVER["SERVER_NAME"] ?? "unknown") . "</p>";

// A tiny write test for file-system examples.
$testFile = "xampp_write_test.txt";
if (file_put_contents($testFile, "Apache and PHP can write here.", LOCK_EX) !== false) {
	echo "<p>Write test passed: $testFile was created or updated.</p>";
} else {
	echo "<p>Write test failed. Check folder permissions.</p>";
}

echo "<p>Open this page with http://localhost/Demo/diagnostics.php, not file://...</p>";
?>
Addendum Glossary: XAMPP, Localhost And Running PHP
XAMPP
A free local development package for running web-server and database tools on a personal computer.
X
Cross-platform; the guide notes XAMPP is available for systems such as Windows, Linux, and OS X.
Apache
The web server component that serves local PHP pages through a browser.
MySQL
The database component used for relational database examples in the module.
PHP
The server-side scripting language used throughout the forms, sessions, files, and database topics.
Perl
The final component represented by the second P in XAMPP.
htdocs
The local web root folder where XAMPP projects are commonly placed.
Demo
The guide's example project folder created inside htdocs.
.php
The file extension that tells the server the file may contain PHP code.
<?php ?>
The opening and closing PHP tags used to place PHP code inside a file.
echo
The PHP keyword used in the addendum example to output HTML text to the browser.
localhost
The browser address that points to the local computer running Apache.
http://localhost/Demo/test.php
The guide's example URL for running test.php inside the Demo folder.
file://
A direct file-opening path; it should not be used to execute PHP because it bypasses Apache/PHP processing.
XAMPP Control Panel
The tool used to start Apache and MySQL modules for local testing.
phpMyAdmin
A browser-based tool commonly used with XAMPP to manage MySQL databases.
PHP_VERSION
A PHP constant that displays the PHP version being used by the local server.
getcwd()
Useful local diagnostic function that shows the server-side current working directory.
$_SERVER
A PHP superglobal containing server and request information such as SERVER_NAME.
Back to Exam Focus Areas

Classes, Functions, Methods & Attributes

Task-based reference for the complete Internet Programming 622 guide: forms, cookies and sessions, files and directories, SQL and MySQL, and local PHP setup. Each entry explains its purpose, shows a short example, and links to General Module Content.

Coverage: Topics 1–4 and the XAMPP addendum. “Supporting practice” identifies useful coding guidance beyond the guide examples. class on an HTML element is an attribute; the Directory class in Topic 3 is a PHP object with properties and methods.

Choose an Internet Programming task

Find an API name · A–Z

Task 1 · Build and submit an HTML form

<form>, action, and method Study-guide content

Does: Groups controls, identifies the receiving script, and chooses GET or POST. Use it when: collecting input for a PHP handler. GET suits non-sensitive searches; POST suits submissions that process or change data. POST does not encrypt data. Example: <form action="handle.php" method="post">…</form>

Full explanation: form structure · Full explanation: GET and POST

<label for> and control id Study-guide content

Does: Connects visible prompt text to a control. Use it when: making a form understandable and usable, including for assistive technology. The label’s for value must match the control’s id. Example: <label for="email">Email</label><input id="email" name="email">

Full explanation: form structure

Checkboxes, radio buttons, <select>, <option>, and <textarea> Study-guide content

Does: Collects a boolean choice, one choice from a group/list, or longer text. Use it when: the answer format should constrain or guide input. Radio choices share a name; the selected option’s value is submitted. Unselected checkbox/radio keys are omitted. Example: <input type="radio" name="size" value="S">

Full explanation: control types · Full explanation: omitted fields

required, min, max, checked, selected Study-guide content + supporting practice

Does: Adds browser-side required/range checks or marks a choice selected. Use it when: improving form guidance and restoring a choice after validation. Browser checks can be bypassed, so validate on the server too. Example: <input type="number" name="age" min="18" max="60" required>

Full explanation: validation · Full explanation: preserve choices

enctype="multipart/form-data" Supporting practice for the guide’s upload exercise

Does: Encodes a request so it can carry file content. Use it when: a form includes a file input and submits with POST. Example: <form method="post" enctype="multipart/form-data">

Full explanation: upload terms in the Topic 1 glossary

Task 2 · Process and validate a request

$_GET, $_POST, $_REQUEST Study-guide content

Does: Provides request values as PHP associative arrays. Use it when: reading submitted data; select $_GET or $_POST to match the form method. $_REQUEST can combine sources and be ambiguous. Example: $name = $_POST["name"] ?? "";

Full explanation: capturing form data

$_SERVER["REQUEST_METHOD"] Supporting practice

Does: Identifies the HTTP method used for this request. Use it when: separating the first page display from form submission processing. Example: if ($_SERVER["REQUEST_METHOD"] === "POST") { /* process */ }

Full explanation: form processing flow

isset(), empty(), array_key_exists() Study-guide content

Does: Checks whether a key/value is present or empty. Use it when: optional controls may not have been sent or a required field may be blank. empty("0") is true, so choose checks to fit the field’s valid values. Example: if (!isset($_POST["news"])) { /* unchecked */ }

Full explanation: empty form fields · Full explanation: validation

filter_var() and FILTER_VALIDATE_EMAIL Study-guide content

Does: Checks whether a value matches a recognized email format. Use it when: validating a non-empty email field on the server. Example: $valid = filter_var($email, FILTER_VALIDATE_EMAIL) !== false;

Full explanation: server-side validation

htmlspecialchars() Study-guide content

Does: Encodes special characters for safe HTML output. Use it when: displaying submitted text in an HTML page; it prevents submitted markup from being interpreted as page markup. It is output escaping, not validation. Example: echo htmlspecialchars($name, ENT_QUOTES, "UTF-8");

Full explanation: form-data security and XSS

setValue(), setChecked(), setSelected(), validateField() Study-guide helper patterns

Does: Preserves entered text/choices and marks fields with errors after failed validation. Use it when: generating and redisplaying a form. Escape restored values for their HTML context. Example: value="<?= htmlspecialchars($_POST["name"] ?? "", ENT_QUOTES, "UTF-8") ?>"

Full explanation: dynamic forms and validation · Full explanation: helper example

name="languages[]" and multiple Study-guide review exercise

Does: Submits selected options as a PHP array. Use it when: a user may choose more than one item. Example: <select name="languages[]" multiple><option value="PHP">PHP</option></select>

Full explanation: multi-select handler

$_FILES, move_uploaded_file(), finfo Study-guide review exercise + supporting validation

Does: Exposes uploaded-file details, checks content type, and moves a valid upload from PHP’s temporary location. Use it when: handling the guide's JPG/PNG upload task with a 2 MB maximum. Example: move_uploaded_file($_FILES["photo"]["tmp_name"], $destination);

Full explanation: complete upload example

password_hash(), password_verify(), mysqli_prepare() Study-guide review exercise

Does: Stores a one-way password hash, verifies a typed password, and keeps user input out of SQL syntax. Use it when: implementing the guide's secure-login task. Example: $hash = password_hash($password, PASSWORD_DEFAULT);

Full explanation: prepared login query

Task 3 · Preserve state across requests

setcookie() and $_COOKIE Study-guide content

Does: Sends a cookie instruction in the response header and reads cookies returned by the browser. Use it when: remembering a small browser-side preference. Call setcookie() before output; the browser sends the new value on a later request. Example: setcookie("theme", "dark", time() + 3600, "/");

Full explanation: cookie lifecycle · Full explanation: preference example

Cookie attributes: expires, path, domain, secure, httponly, samesite Study-guide parameters + supporting practice

Does: Controls lifetime and where/how the browser sends a cookie. Use it when: setting a cookie’s scope and protection. Secure cookies require HTTPS; HttpOnly limits JavaScript access; SameSite helps constrain cross-site sending. Example: setcookie("theme", "dark", ["expires" => time()+3600, "path" => "/", "secure" => true, "httponly" => true, "samesite" => "Lax"]);

Full explanation: cookie parameters

time() Study-guide content

Does: Returns the current Unix timestamp. Use it when: calculating a cookie expiry in seconds. Example: $expires = time() + 7 * 24 * 60 * 60;

Full explanation: cookie expiry

session_start() and $_SESSION Study-guide content

Does: Starts/resumes a session and provides its server-side values. Use it when: preserving login or multi-step form data between pages. Call it before output on every page that uses the session. Example: session_start(); $_SESSION["step"] = 2;

Full explanation: session lifecycle · Full explanation: login flow

session_id(), session_name(), session_get_cookie_params() Study-guide API + supporting logout details

Does: Reads the current session identifier/name and configured cookie parameters. Use it when: examining session setup or expiring the session cookie during logout. Do not reveal session IDs in URLs or page output. Example: $params = session_get_cookie_params();

Full explanation: session IDs · Full explanation: logout code

session_destroy() and unset() Study-guide content + supporting practice

Does: Removes session data; unset() removes a selected session value. Use it when: logging out or clearing one saved step. For full logout, clear $_SESSION, destroy session data, and expire the session cookie. Example: $_SESSION = []; session_destroy();

Full explanation: ending a session · Full explanation: logout code

header(), exit, session_regenerate_id() Supporting authentication practice

Does: Sends a redirect, stops script execution, and replaces the session ID. Use it when: redirecting after a login/logout transition and regenerating the ID after authentication. Send headers before output. Example: session_regenerate_id(true); header("Location: welcome.php"); exit;

Full explanation: session login example

Task 4 · Inspect, read, and write files

file_exists(), filesize() Study-guide content

Does: Tests whether a path exists and reports a file's size in bytes. Use it when: checking a file before opening it. Example: if (file_exists("data.txt")) echo filesize("data.txt"); filesize() can return false on error.

Full explanation: file metadata

fileatime(), filectime(), filemtime(), date() Study-guide content

Does: Reads access, change, and modification timestamps; date() formats a timestamp. Use it when: displaying file history. filectime() is metadata change time on Unix-like systems, not a portable creation time. Example: echo date("Y-m-d", filemtime("data.txt"));

Full explanation: time-related properties

basename(), dirname() Study-guide content

Does: Extracts the final name or parent directory from a path. Use it when: separating a path for display or navigation. These functions parse strings; they do not confirm that the path exists. Example: basename("/docs/report.txt") gives report.txt; dirname("/docs/report.txt") gives /docs.

Full explanation: paths · Directory functions

fopen(), fclose() Study-guide content

Does: Opens a file handle in a chosen mode and closes it. Use it when: reading or writing incrementally. r needs an existing file; w truncates; a appends. Example: $h = fopen("log.txt", "a"); if ($h !== false) { fwrite($h, "OK\n"); fclose($h); }

Full explanation: open modes

fread(), fgetc(), fgets(), feof() Study-guide content

Does: Reads a byte count, one character, or one line; feof() reports end of file. Use it when: processing a large file in pieces. For lines, test the read result so the final line is not skipped. Example: while (($line = fgets($h)) !== false) echo htmlspecialchars($line, ENT_QUOTES, "UTF-8");

Full explanation: reading files · EOF

fgetcsv() Study-guide review exercise

Does: Parses the next CSV row into an array. Use it when: reading the guide's name,age,city table without splitting quoted commas incorrectly. Example: while (($row = fgetcsv($h)) !== false) { /* escape each cell */ }

Full explanation: CSV table

fwrite(), file_put_contents() Study-guide content

Does: Writes through an open handle or writes a whole string in one call. Use it when: saving text; use FILE_APPEND to keep existing content with the whole-file function. Example: file_put_contents("log.txt", "New entry\n", FILE_APPEND); Check the return value for false.

Full explanation: writing files

file(), file_get_contents() Study-guide content

Does: Reads a whole file as an array of lines or one string. Use it when: the file is small enough to fit comfortably in memory. Example: $lines = file("notes.txt", FILE_IGNORE_NEW_LINES); Test for false before using the result.

Full explanation: whole-file reads

readfile(), fpassthru() Study-guide content

Does: Sends file contents to output; fpassthru() starts at the current position of an open handle. Use it when: returning trusted file contents directly. Do not send untrusted HTML into a page without escaping it. Example: readfile("public.txt"); or fpassthru($h);

Full explanation: entire-file functions

fseek(), ftell(), rewind() Study-guide content

Does: Moves, reports, or resets the file pointer. Use it when: reading a known position in a file. Example: fseek($h, 7); echo fread($h, 5); rewind($h); A successful fseek() returns 0.

Full explanation: random access

rb, wb, strlen() Study-guide binary review exercise

Does: Opens binary files for reading/writing and counts bytes in a binary string. Use it when: copying image or other non-text data. Example: $h = fopen("sample.png", "rb"); $bytes = fread($h, filesize("sample.png")); echo strlen($bytes);

Full explanation: binary copy

copy(), rename(), unlink() Study-guide content

Does: Copies, moves/renames, or deletes a file. Use it when: managing a known server path. Example: if (is_file("report.txt")) copy("report.txt", "backup.txt"); Check the return value and verify a target before unlink().

Full explanation: file management

Task 5 · Navigate directories

opendir(), readdir(), closedir(), rewinddir() Study-guide content

Does: Opens a directory, reads entries, closes it, or resets its pointer. Use it when: listing contents. Skip . and ..; compare reads with !== false. Example: while (($name = readdir($handle)) !== false) { if ($name !== "." && $name !== "..") echo htmlspecialchars($name); }

Full explanation: directory handles

dir(), Directory, path, handle Study-guide class and properties

Does: dir() creates a Directory object; its path and handle properties expose the directory path and underlying handle. Use it when: following the guide's object-oriented directory pattern. Example: $dir = dir("files_dir"); if ($dir !== false) echo $dir->path;

Full explanation: Directory object

Directory::read(), Directory::rewind(), Directory::close() Study-guide methods

Does: Reads the next entry, starts again from the first entry, and closes the directory. Use it when: traversing with a Directory object. Example: while (($name = $dir->read()) !== false) { /* use $name */ } $dir->rewind(); $dir->close();

Full explanation: methods and full example

chdir(), getcwd(), mkdir(), rmdir() Study-guide content

Does: Changes/reports the working directory or creates/removes a directory. Use it when: handling directory paths. rmdir() only removes an empty directory; changing working directory also changes how relative paths resolve. Example: if (!is_dir("reports")) mkdir("reports"); echo getcwd();

Full explanation: directory functions

is_file(), is_dir() Study-guide content

Does: Distinguishes a regular file from a directory. Use it when: choosing how to process a path found while listing entries. Example: if (is_dir($path)) echo "Folder"; elseif (is_file($path)) echo "File";

Full explanation: file versus directory

Task 6 · Create and change database data with SQL

CREATE DATABASE, USE, CREATE TABLE Study-guide SQL

Does: Creates a database, selects it, and defines a table. Use it when: setting up the guide's fruit exercise. Example: CREATE DATABASE mydatabase; USE mydatabase; CREATE TABLE fruit (id INT PRIMARY KEY, name VARCHAR(30));

Full explanation: database and table setup

PRIMARY KEY, AUTO_INCREMENT, INDEX Study-guide SQL attributes

Does: Uniquely identifies rows, generates numeric IDs, and speeds lookups. Use it when: designing relational tables. Example: id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (id). An index helps reads but adds work to writes.

Full explanation: indexes and keys · Table example

INSERT INTO, SELECT, WHERE Study-guide SQL

Does: Adds rows, reads rows, and filters the rows returned or changed. Use it when: doing create/read work. Example: INSERT INTO fruit (name, color) VALUES ('plum', 'purple'); SELECT name FROM fruit WHERE color = 'purple';

Full explanation: CRUD

UPDATE, DELETE, DROP TABLE Study-guide SQL

Does: Changes selected rows, removes selected rows, or removes the table structure. Use it when: modifying or cleaning up data. Example: UPDATE fruit SET color = 'red' WHERE id = 2; DELETE FROM fruit WHERE id = 3; Omitting WHERE affects every row; DROP TABLE fruit removes the table.

Full explanation: update and delete

INNER JOIN, SUM(), GROUP BY, ALTER TABLE Study-guide review questions

Does: Connects related tables, totals grouped rows, and changes table structure. Use it when: answering the Customers/Orders review tasks. Example: SELECT c.Name, SUM(o.TotalAmount) FROM Customers c INNER JOIN Orders o ON c.CustomerID = o.CustomerID GROUP BY c.CustomerID, c.Name;

Full explanation: review query patterns · Extended worked example

Task 7 · Connect PHP to MySQL and read rows

mysqli_connect(), mysqli_connect_error(), mysqli_close() Study-guide content

Does: Opens a MySQL connection, reports a connection error, and closes it. Use it when: running the guide's procedural MySQL example. Example: $conn = mysqli_connect("localhost", "root", "", "mydatabase"); if (!$conn) die(mysqli_connect_error()); /* queries */ mysqli_close($conn); Modern PHP may throw a mysqli_sql_exception instead of returning false when strict reporting is enabled.

Full explanation: PHP connection

mysqli_query(), mysqli_error() Study-guide content

Does: Runs SQL and exposes an error if the query fails. Use it when: executing a fixed SQL statement. Example: $result = mysqli_query($conn, "SELECT * FROM fruit"); if (!$result) die(mysqli_error($conn)); Use prepared statements for values supplied by users.

Full explanation: query errors

mysqli_fetch_assoc(), mysqli_free_result() Study-guide content and supporting cleanup

Does: Fetches a result row as a named array; optional cleanup releases the result set. Use it when: displaying rows returned by SELECT. Example: while ($row = mysqli_fetch_assoc($result)) echo htmlspecialchars($row["name"], ENT_QUOTES, "UTF-8"); mysqli_free_result($result);

Full explanation: complete fruit reader

PDO, mysqli Study-guide API choices

Does: Names PHP's two database access options discussed by the guide. Use it when: choosing a database interface; the guide's worked connection and fetch code uses procedural mysqli. Example: mysqli_connect("localhost", "root", "", "mydatabase").

Full explanation: PHP database interfaces

Task 8 · Run PHP on your computer

.php, htdocs, localhost Study-guide addendum

Does: Identifies a PHP script, XAMPP's document folder, and the local web-server address. Use it when: testing a script through Apache. Example: save Demo/test.php under htdocs, start Apache, then open http://localhost/Demo/test.php.

Full explanation: running PHP · URL and folder mapping

Learning Lab

Use these interactive tools to practise each Internet Programming topic. Your quiz attempts are saved only in this browser.

Quiz Builder

Choose how many questions to draw from each topic, then answer and submit when ready.

Flashcards

Recall the definition before flipping the card.

Concept Checker

Internet Programming Video Resources

Selected lessons mapped to the topics in this guide. Topics 1 and 2 match the confirmed current test scope; Topics 3 and 4 are supporting resources for the wider module, not confirmed content for that test.

Online resource: YouTube embeds and links require an internet connection. The rest of the guide remains available offline. Videos supplement the supplied study guide; where versions or code styles differ, follow the guide’s stated scope and examples.

Topic 1 · PHP and HTML Forms Confirmed test scope

Topic 1 · Form handling

Follow how submitted form data reaches PHP and is handled. Pair the examples with the guide’s action/method and GET/POST explanations.

Dani Krossing

Open this video on YouTube

Topic 1 · Validation

A focused example of checking required input. The course guide covers the wider validation, redisplay, and output-escaping patterns.

The Net Ninja

Open this video on YouTube

Topic 2 · Sessions and Cookies Confirmed test scope

Topic 2 · Sessions

Explains session state across page requests. Compare the video workflow with the guide’s session_start(), $_SESSION, and logout explanations.

The Net Ninja

Open this video on YouTube

Topic 2 · Cookies

Covers browser cookies. Use the guide for the cookie lifecycle, expiry, and the difference between cookies and sessions.

The Net Ninja

Open this video on YouTube

Topic 3 · File System Management Wider module support

Topic 3 · File system, part 1

Introduces reading and writing files in PHP, matching the file-handling topic in the module guide.

The Net Ninja

Open this video on YouTube

Topic 3 · File system, part 2

Follow-on lesson for the file-system examples. Use it alongside the guide’s file pointers, directories, and CSV sections.

The Net Ninja

Open this video on YouTube

Topic 4 · Databases and SQL Wider module support

Topic 4 · Database setup

Shows creating the database used by a PHP website; the guide adds database architecture and table-structure notes.

Dani Krossing

Open this video on YouTube

Topic 4 · SQL SELECT and JOIN

Practise retrieving and joining table data. The guide provides additional query patterns and exam-style examples.

Dani Krossing

Open this video on YouTube

Topic 4 · Connect PHP to MySQL

Demonstrates a PHP database connection using PDO. The module guide also shows procedural mysqli, so compare the common connection/query steps.

Dani Krossing

Open this video on YouTube

Topic 4 · Insert, update, and delete

Shows form-to-database insertion and prepared statements. For UPDATE and DELETE, pair it with the next targeted lesson.

Dani Krossing

Open this video on YouTube

Topic 4 · UPDATE and DELETE

Shows changing and deleting database records from PHP forms; compare the SQL with the guide’s warnings about DELETE conditions.

Dani Krossing

Open this video on YouTube

Internet Programming 621 · Previous Study Reference

Complete archived copy of the previous semester’s Internet Programming 621 study guide. Its notes and exam focus belong to that course and are included for reference; they do not define Internet Programming 622 test scope. Use the guide’s own Menu to move between its sections.