University Examination Solutions · Computer Applications / IT
Table of Contents
To secure full marks in Group A, candidates must state the correct option and provide a concise, theoretically sound justification citing standard PHP/MySQL mechanics.
$). The character immediately following the dollar sign must be a letter (a-z, A-Z) or an underscore (_). It cannot be a number, and PHP variable names are case-sensitive (e.g., $var and $Var represent distinct memory locations).
.php. When a client requests a file ending in .php, the web server (such as Apache or Nginx) routes the file through the integrated PHP Preprocessor engine before outputting pure HTML back to the client.
local, global, and static scopes. An extern scope is a linkage classification used in compiled languages like C and C++ to refer to variables declared in different file modules. It is syntactically invalid and unrecognized in PHP.
echo and print are language constructs used to display output. The main functional differences are: echo can accept multiple comma-separated arguments and has no return value, whereas print accepts only one argument and always returns 1 (allowing it to be used in expression contexts).
strlen(string $string): int calculates and returns the number of bytes (representing characters in single-byte character sets) in a given string. For multi-byte unicode strings, mb_strlen() is preferred.
Trigger is a procedural block of code that is automatically executed ("fired") by the database engine in response to specific modification events (such as INSERT, UPDATE, or DELETE) on a specified table.
<?php function test(){ static $count = 0; $count++; echo $count; } test(); test(); test(); ?>static keyword preserves its value across sequential function execution scopes. The first call to test() initializes `$count` to `0`, increments it to `1`, and outputs `1`. The subsequent calls bypass re-initialization, incrementing the preserved value to `2` and `3` respectively, producing `123`.
setcookie() function defines a cookie to be sent along with the rest of the HTTP headers to the client. It must be executed before any actual HTML output is sent, as headers must precede body content.
isset(mixed $var, mixed ...$vars): bool returns true if the variable is declared, set, and is not null. It is a critical check to avoid Undefined Variable or Undefined Index runtime notices.
array_push(array &$array, mixed ...$values): int treats the array as a stack and pushes the passed variables onto the end of that array, returning the new total element count.
select_db() method on a instantiated MySQLi database connection object (conventionally named $mysqli).
80 is default for standard, unencrypted HTTP. Therefore, "None of the above" is the correct choice here.
session_start() creates a new session or resumes an existing one based on a session identifier passed via an HTTP request cookie or a GET parameter.
fopen() binds a named file resource to a stream. The mode parameter "r" opens the target file for reading only with the pointer placed at the beginning of the file. Mode "r+" opens for both reading and writing, which is incorrect when read-only access is specified.
global keyword declarations. Other superglobals include $_SESSION, $_COOKIE, $_FILES, $_SERVER, $_ENV, and $_REQUEST.
Role in Developing Dynamic Internet Applications:
| Feature Metric | Static Websites | Dynamic Websites |
|---|---|---|
| Content Source | Fixed HTML/CSS files pre-authored and saved directly on the host server storage. | Compiled in real-time, pulling records from database schemas dynamically. |
| Interactive Ability | Extremely low. Displays the same static pages to every single visitor. | High. Tailors pages based on session states, user profiles, or inputs. |
| Database Connection | None. No direct interaction with database management engines. | Highly coupled with relational (SQL) or non-relational (NoSQL) databases. |
| Maintenance Complexity | High. Every content change requires modifying the source code of each individual HTML file. | Low. Updates are made in the database or a CMS dashboard, instantly updating all pages. |
Operators are syntax symbols that perform operations on one or more values (operands). PHP supports several major operator classes:
| Operator Class | Syntax Represented | Description & Behavioral Rules |
|---|---|---|
| Arithmetic Operators | +, -, *, /, %, ** |
Used to perform standard mathematical calculations. % yields the remainder of a division, while ** performs exponentiation. |
| Comparison Operators | ==, ===, !=, !==, <, > |
Compares two values. Note that == checks for value equality after type coercion, while === enforces strict identity checking (both value and data type). |
| Logical Operators | && (and), || (or), ! (not) |
Used to combine conditional statements. && returns true only if both operands are true, while || returns true if at least one operand is true. |
| Assignment Operators | =, +=, -=, *=, .= |
Used to write values to variables. .= is the concatenation assignment operator, which appends the right-hand string to the left-hand variable. |
$ sign.$userLimit = 100;define() or the const keyword. No leading $ is used.const API_VERSION = "v2.4";The scope of a variable defines where it can be accessed or modified within a script. PHP enforces three distinct scopes:
function calc() { $x = 10; echo $x; } // $x is inaccessible outside calc()
global keyword or reference the superglobal $GLOBALS array.
$g = 50;
function access() { global $g; echo $g; /* Or: echo $GLOBALS['g']; */ }
static preserves its value across sequential function calls, allowing it to act as a local accumulator.
function tracker() { static $hits = 0; $hits++; echo $hits; }
| Feature Comparison | The standard FOR Statement Loop | The FOREACH Statement Loop |
|---|---|---|
| Primary Use Case | Best for executing a block of code a specific number of times when the iteration limit is known in advance. | Specifically designed to iterate over arrays or object elements without needing to manage a manual counter. |
| Index Dependency | Requires explicit index initialization, logical condition checking, and manual increment/decrement steps. | Automatically handles pointer navigation internally, moving through each key/value pair sequentially. |
| Associative Array Support | Inefficient for associative arrays with non-numeric, custom string keys. | Native support. Easily maps keys and values using the as $key => $value syntax. |
<?php
// Standard FOR Loop execution
for ($i = 0; $i < 3; $i++) {
echo "Counter: $i | ";
}
echo "\n";
// Dynamic FOREACH Loop traversing an Associative Array
$memberRoles = ["Admin" => "John", "Editor" => "Sara"];
foreach ($memberRoles as $role => $name) {
echo "$name is the $role | ";
}
?>
Uses sequential, zero-indexed integers as keys to reference stored elements.
$cities = ["Paris", "Tokyo", "Cairo"];
Accessible via numeric indices: $cities[0] yields "Paris".
Uses developer-defined, semantic strings as keys to access mapped values.
$salaries = ["Alice" => 75000, "Bob" => 62000];
Accessible via string keys: $salaries["Alice"] yields 75000.
PHP provides highly optimized, built-in sorting functions. Key functions include:
sort(): Sorts an indexed array's values in ascending order.asort(): Sorts an associative array's values in ascending order while maintaining key-value associations.ksort(): Sorts an associative array by its keys in ascending order.<?php
$students = ["Mark" => 88, "Alice" => 95, "Zack" => 79];
// Sort by value, preserving key associations (ascending)
asort($students);
print_r($students);
/* Output:
Array (
[Zack] => 79
[Mark] => 88
[Alice] => 95
) */
// Sort alphabetically by key (ascending)
ksort($students);
print_r($students);
/* Output:
Array (
[Alice] => 95
[Mark] => 88
[Zack] => 79
) */
?>
PHP supports passing parameters to functions both by value (default) and by reference.
When an argument is passed by value, a copy of the variable's value is passed into the function's scope. Modifications inside the function do not affect the original variable.
function addFive($num) {
$num += 5;
}
$val = 10;
addFive($val);
// $val is still 10
Passing by reference passes the memory address of the original variable into the function using the & symbol. Modifications inside the function directly alter the original variable's value.
function addFiveRef(&$num) {
$num += 5;
}
$val = 10;
addFiveRef($val);
// $val is now 15
Default arguments allow you to define default values for parameters. If the caller does not pass a value for that parameter, the function will use the pre-assigned default value instead.
<?php
// Default values are defined directly in the function signature
function generateTaxInvoice($baseAmount, $taxRate = 18) {
$tax = ($baseAmount * $taxRate) / 100;
return $baseAmount + $tax;
}
// Case 1: Caller overrides the default tax rate parameter
echo "Custom Rate (5%): " . generateTaxInvoice(1000, 5) . "\n"; // Yields 1050
// Case 2: Caller omits the second parameter, falling back to 18%
echo "Default Rate (18%): " . generateTaxInvoice(1000) . "\n"; // Yields 1180
?>
Data Manipulation Language (DML) statements are used to manage data within existing database schemas. Key DML statements include:
Inserts new records into an existing table structure.
INSERT INTO customers (name, email) VALUES ('Alex', 'alex@email.com');
Modifies existing data records within a table. Always pair with a WHERE clause to avoid updating all rows.
UPDATE customers SET status = 'Active' WHERE id = 12;
PHP provides two main object-oriented extensions for connecting to and interacting with MySQL databases:
| Evaluation Basis | MySQLi Extension (MySQL Improved) | PDO Extension (PHP Data Objects) |
|---|---|---|
| Database Portability | Strictly limited to MySQL databases. | Supports 12 different database engines (including PostgreSQL, SQLite, MS SQL, and Oracle). |
| API Syntax Style | Supports both procedural and object-oriented interfaces. | Strictly object-oriented, providing a consistent abstraction layer. |
| Named Parameters | Not supported in prepared statements (uses ? placeholders). |
Fully supported (e.g., :email), making queries easier to read and maintain. |
| Prepared Statements | Supported, but implementation is complex compared to PDO. | Fully integrated, providing robust protection against SQL injection. |
PHP has built-in functions designed for string manipulation, which are essential for validation and parsing:
strpos(string $haystack, string $needle): int|false: Finds the position of the first occurrence of a substring. Returns false if the substring is not found.str_replace(mixed $search, mixed $replace, mixed $subject): mixed: Replaces all occurrences of a search string with a replacement string within a target string.trim(string $string): string: Strips whitespace (or other specified characters) from the beginning and end of a string.<?php
// 1. Setting a Cookie (Expires in 1 hour, accessible across the site)
$cookieValue = "Jane Doe";
setcookie("user_profile", $cookieValue, time() + 3600, "/");
// 2. Viewing/Accessing a Cookie (Using the $_COOKIE superglobal)
if (isset($_COOKIE["user_profile"])) {
echo "Welcome back, " . htmlspecialchars($_COOKIE["user_profile"]) . "!";
} else {
echo "No profile cookie found.";
}
// 3. Deleting a Cookie (Set the expiration time to the past)
setcookie("user_profile", "", time() - 3600, "/");
?>
To clear a specific variable from an active session, use the unset() function on the target key within the $_SESSION superglobal array.
<?php
session_start();
// Unset a specific session variable
unset($_SESSION['cart_items']);
// To unset all session variables at once (safer than reassigning $_SESSION)
session_unset();
?>
MVC is a software design pattern that separates an application into three interconnected components, dividing business logic from the user interface.
Model-View-Controller (MVC) Data Flow & Interactions
The leading PHP framework, known for its clean syntax, robust ORM (Eloquent), built-in authentication routing, and helper ecosystem (Blade engine, Artisan CLI).
A lightweight, fast MVC framework designed for speed and simplicity. It features a minimal footprint, zero configuration, and clear documentation.
A highly professional, modular framework built with decoupled PHP components. It is widely used for enterprise-level applications due to its stability and configurability.
To safely insert dynamic web data into a relational database, you must follow these steps:
$_POST superglobal) and validate or sanitize it to ensure it matches the expected format.INSERT INTO statement with parameter placeholders (rather than direct string concatenation) to prevent SQL injection.This script securely processes incoming form data submitted via the POST method and writes it to a MySQL database using the MySQLi extension.
<?php
// Database credentials
$host = "localhost";
$dbUser = "admin_root";
$dbPass = "app_pass_321";
$dbSchema = "catalog_db";
// 1. Establish an object-oriented connection to MySQLi
$mysqli = new mysqli($host, $dbUser, $dbPass, $dbSchema);
// Verify connection integrity
if ($mysqli->connect_error) {
die("Database Connection Error: " . $mysqli->connect_error);
}
// 2. Intercept and process POST data
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Retrieve and sanitize inputs
$itemTitle = trim($_POST['itemTitle'] ?? '');
$itemPrice = floatval($_POST['itemPrice'] ?? 0.0);
// Validate inputs
if (!empty($itemTitle) && $itemPrice > 0) {
// 3. Prepare the SQL insert statement using parameter placeholders
$sql = "INSERT INTO products (title, price) VALUES (?, ?)";
$stmt = $mysqli->prepare($sql);
if ($stmt) {
// 4. Bind variables to the prepared statement as parameters
// "sd" denotes types: s = string, d = double (float)
$stmt->bind_param("sd", $itemTitle, $itemPrice);
// 5. Execute query and verify status
if ($stmt->execute()) {
echo "<div class='key-point'><span class='klabel'>Success</span>Product successfully written to inventory.</div>";
} else {
echo "<div class='warning'><span class='wlabel'>Database Error</span>" . $stmt->error . "</div>";
}
// Close statement
$stmt->close();
} else {
echo "Failed to compile SQL statement.";
}
} else {
echo "<div class='warning'><span class='wlabel'>Validation Failure</span>Please provide a valid product title and positive price.</div>";
}
}
// Close connection
$mysqli->close();
?>
Provides functions to simplify generating links and routing redirects inside views.
base_url(), site_url(), anchor(), redirect()
Automates generating secure HTML form elements and retaining validated values.
form_open(), form_input(), form_close(), set_value()
Provides a clean interface for reading, writing, and deleting client-side cookies.
set_cookie(), get_cookie(), delete_cookie()
Simplifies file system interactions like reading, writing, and listing directories.
read_file(), write_file(), get_filenames()
Helpers must be explicitly loaded before their functions can be called. This can be done dynamically inside a controller method or globally via the autoload configuration.
// CodeIgniter 3/4 Controller Implementation
class AccountController extends CI_Controller {
public function register() {
// Dynamic loading of URL and Form helpers
$this->load->helper(['url', 'form']);
// Use helper functions directly
$formDestination = site_url('account/save');
// Load target registration view
$this->load->view('register_form', ['target' => $formDestination]);
}
}
// In CodeIgniter 4, you can also use helper() directly:
// helper(['url', 'form']);
Key takeaways and common student traps to keep in mind for descriptive questions.
Security & Scope Rules
API & Import Comparisons
Web Designing Past Paper Solutions · Hand-crafted Exam Notes · Aligned with June 2024 Syllabus Guidelines.