University Examination Solutions · Computer Applications / IT

Web Designing

June 2024 Past-Paper Solutions & Academic Reference Notes

PHP Architecture MySQLi & PDO State persistence MVC Architecture Database Triggers CodeIgniter Helpers

Table of Contents

  1. Group A: Multiple Choice Questions & Analytical Explanations
  2. Question 2: PHP Basics, Dynamic Web Apps, & Operator Evaluation
  3. Question 3: Variables, Constants, Scopes, & Control Flows
  4. Question 4: Array Implementations & Custom Sorting Mechanics
  5. Question 5: Functions, Arguments, Call-by-Value & Call-by-Reference
  6. Question 6: MySQL Data Manipulation & PHP Connection APIs
  7. Question 7: String Operations, State persistence (Cookies & Sessions)
  8. Question 8: Web Framework Architecture, MVC & Global Framework Comparison
  9. Question 9: Dynamic Database Insertion & Secure Form Integration
  10. Question 10: CodeIgniter Helpers: Design, Types, & Loading Mechanisms
  11. High-Yield Exam Core Points
  12. Quick Revision Matrix
Group A - MCQs

Group A: Multiple Choice Questions (2 × 10 = 20 Marks)

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.

i. Variable name in PHP starts with -
a) !    b) $    c) &    d) None of them Correct Option: b) $
Academic Explanation All PHP variables must be declared with a leading dollar sign ($). 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).
ii. Which of the following is the default file extension of PHP?
a) .xphp    b) .hphp    c) .php    d) None of them Correct Option: c) .php
Academic Explanation The standard and default extension of a PHP script file is .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.
iii. Which of the following is not a variable scope in PHP?
a) extern    b) local    c) static    d) global Correct Option: a) extern
Academic Explanation PHP supports 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.
iv. Which of the following is used to display the output in PHP?
a) echo    b) print    c) write    d) both (a) & (b) Correct Option: d) both (a) & (b)
Academic Explanation Both 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).
v. Which of the following is the use of strlen() function in PHP?
a) The strlen() function returns the type of string
b) The strlen() function returns the length of string
c) The strlen() function returns the value of string
d) The strlen() function returns both value and type of string Correct Option: b) The strlen() function returns the length of string
Academic Explanation The built-in function 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.
vi. What is defined to execute when the table is modified only in MySQL?
a) Stored functions    b) Stored procedures    c) Triggers    d) Events Correct Option: c) Triggers
Academic Explanation A database 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.
vii. What will be the output of the following code?
<?php function test(){ static $count = 0; $count++; echo $count; } test(); test(); test(); ?>
a) 111    b) 012    c) 123    d) 000 Correct Option: c) 123
Academic Explanation A variable declared with the 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`.
viii. Which of the following function is used to set cookie in PHP?
a) createcookie()    b) makecookie()    c) setcookie()    d) None of the above Correct Option: c) setcookie()
Academic Explanation The 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.
ix. What is the use of isset() function in PHP?
a) The isset() function is used to check whether variable is set or not
b) The isset() function is used to check whether the variable is free or not
c) The isset() function is used to check whether the variable is string or not
d) None of the above Correct Option: a) The isset() function is used to check whether variable is set or not
Academic Explanation The function 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.
x. Which of the following is a built-in function in PHP that adds a value to the end of an array?
a) array_push()    b) incnd_array()    c) into_array()    d) None of the above Correct Option: a) array_push()
Academic Explanation The function 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.
xi. Which one of the following statements can be used to select the database?
a) $mysqli = select_db('databasename');
b) mysqli = select_db('databasename');
c) mysqli->select_db('databasename');
d) $mysqli->select_db('databasename'); Correct Option: d) $mysqli->select_db('databasename');
Academic Explanation Using the object-oriented MySQLi extension in PHP, database selection is executed by calling the select_db() method on a instantiated MySQLi database connection object (conventionally named $mysqli).
xii. What is the default port number of HTTPS?
a) 80    b) 8000    c) 8080    d) None of the above Correct Option: d) None of the above
Academic Explanation The default TCP port for HTTPS (Hypertext Transfer Protocol Secure) is 443. Port 80 is default for standard, unencrypted HTTP. Therefore, "None of the above" is the correct choice here.
xiii. Which one of the following function is used to start a session?
a) start_session()    b) session_start()    c) session_begin()    d) begin_session() Correct Option: b) session_start()
Academic Explanation The native function 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.
xiv. Which of the following is the correct way to open the file "MyFile.txt" as readable?
a) fopen("MyFile.txt","r");    b) fopen("MyFile.txt","r+");    c) fopen("MyFile.txt","read");    d) fopen("MyFile.txt") Correct Option: a) fopen("MyFile.txt","r");
Academic Explanation The native function 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.
xv. Which is / are superglobal variables in PHP?
a) $_GET    b) $GLOBALS    c) $_POST    d) All of the above Correct Option: d) All of the above
Academic Explanation Superglobals are built-in, associative array variables in PHP that are always available in all scopes throughout the script execution lifecycle without requiring explicit global keyword declarations. Other superglobals include $_SESSION, $_COOKIE, $_FILES, $_SERVER, $_ENV, and $_REQUEST.

Question 2

2. PHP Basics, Dynamic Web Apps, & Operator Evaluation (3+3+2 Marks)

a) Definition of PHP & Its Role in Dynamic Applications

Definition — PHP (Hypertext Preprocessor) PHP is an open-source, server-side, interpreted scripting language designed specifically for web development. It is embedded within HTML source documents to execute server-side business logic and generate dynamic web content.

Role in Developing Dynamic Internet Applications:

b) Static vs. Dynamic Websites

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.

Key Advantages of Dynamic Websites:

  1. Highly Interactive & Personalized: Delivers unique experiences, such as user dashboards, personalized shopping recommendations, and localized content based on user profiles.
  2. Centralized Data Management: Content updates can be easily made via a Content Management System (CMS) or database, eliminating the need to edit static HTML code across thousands of files.
  3. Scalability: Managing massive systems (such as e-commerce catalogs or news hubs) is efficient, as a single dynamic template file can render millions of unique product pages on demand.

c) Evaluation of Key Operators in PHP

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.

Question 3

3. Variables, Constants, Scopes, & Control Flows (2+3+3 Marks)

a) Variables and Constants in PHP

PHP Variables
  • • Declared with a leading $ sign.
  • • Values can be reassigned during script execution.
  • • Weakly and dynamically typed; data types are determined automatically at runtime.
  • • Example: $userLimit = 100;
PHP Constants
  • • Declared using define() or the const keyword. No leading $ is used.
  • • Values cannot be changed or redefined once set.
  • • Globally scoped automatically; accessible across functions and classes.
  • • Example: const API_VERSION = "v2.4";

b) Variable Scopes in PHP

The scope of a variable defines where it can be accessed or modified within a script. PHP enforces three distinct scopes:

  1. Local Scope: A variable declared inside a function has local scope and can only be accessed within that function.
    function calc() { $x = 10; echo $x; } // $x is inaccessible outside calc()
  2. Global Scope: A variable declared outside functions has global scope. To access a global variable inside a function, use the global keyword or reference the superglobal $GLOBALS array.
    $g = 50;
    function access() { global $g; echo $g; /* Or: echo $GLOBALS['g']; */ }
  3. Static Scope: Typically, local variables are destroyed when a function finishes executing. Declaring a variable as static preserves its value across sequential function calls, allowing it to act as a local accumulator.
    function tracker() { static $hits = 0; $hits++; echo $hits; }

c) Structural Difference: FOR vs. FOREACH Loops

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.
Code Demonstration: Loop Syntaxes in PHP
<?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 | ";
}
?>

Question 4

4. Array Implementations & Custom Sorting Mechanics (1+4+3 Marks)

a) What is an Array in PHP?

Formal Definition — Array An array is an ordered mapping structure that stores multiple values under a single variable name. It associates values with keys, acting as an optimized, multi-type collection interface.

b) Indexed vs. Associative Arrays

1. Indexed Arrays

Uses sequential, zero-indexed integers as keys to reference stored elements.

$cities = ["Paris", "Tokyo", "Cairo"];

Accessible via numeric indices: $cities[0] yields "Paris".

2. Associative Arrays

Uses developer-defined, semantic strings as keys to access mapped values.

$salaries = ["Alice" => 75000, "Bob" => 62000];

Accessible via string keys: $salaries["Alice"] yields 75000.

c) Sorting Functions and Custom Implementations

PHP provides highly optimized, built-in sorting functions. Key functions include:

Example: Sorting Associative Arrays in PHP
<?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
) */
?>

Question 5

5. Functions, Arguments, Call-by-Value & Call-by-Reference (3+3+2 Marks)

a) Function Parameter Passing Mechanics

PHP supports passing parameters to functions both by value (default) and by reference.

i) Passing Arguments by Value

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
ii) Passing Arguments by Reference

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

b) Default Arguments in PHP Functions

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.

Academic Rule for Parameters All parameters with default values must be declared to the right of any parameters without default values. Declaring a default parameter before a mandatory parameter is a syntactic error.
Example Code: Function with Default Arguments
<?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
?>

Question 6

6. MySQL Data Manipulation & PHP Connection APIs (2+2+4 Marks)

a) Data Manipulation in MySQL

Data Manipulation Language (DML) statements are used to manage data within existing database schemas. Key DML statements include:

1. INSERT Statement

Inserts new records into an existing table structure.

INSERT INTO customers (name, email) VALUES ('Alex', 'alex@email.com');
2. UPDATE Statement

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;

b) PHP Database Connection APIs: MySQLi vs. PDO

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.

Question 7

7. String Operations, State persistence (Cookies & Sessions) (2+4+2 Marks)

a) Standard String Functions in PHP

PHP has built-in functions designed for string manipulation, which are essential for validation and parsing:

b) Cookies in PHP: Setting, Viewing, and Deleting

Definition — Cookie A cookie is a small text file stored locally on the client's browser. It allows the server to identify unique users, track sessions, and store persistent preferences.
Example PHP Script: Complete Cookie Lifecycle
<?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, "/");
?>

c) Unsetting Session Variables in PHP

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();
?>

Question 8

8. Web Framework Architecture, MVC & Global Framework Comparison (2+4+2 Marks)

a) What is a PHP Framework?

Formal Definition — Web Framework A PHP framework is a pre-architected library of classes, helper methods, and structural rules designed to streamline web development. It implements industry-standard design patterns, helping developers avoid redundant boilerplate code.

b) The MVC (Model-View-Controller) Architectural Pattern

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

User Browser Controller Model (Data) View (UI) 1. Request 2. Queries 3. Populates 4. Renders HTML

Significance of MVC in Web Development:

c) Popular PHP Frameworks & Key Features

1. Laravel

The leading PHP framework, known for its clean syntax, robust ORM (Eloquent), built-in authentication routing, and helper ecosystem (Blade engine, Artisan CLI).

2. CodeIgniter

A lightweight, fast MVC framework designed for speed and simplicity. It features a minimal footprint, zero configuration, and clear documentation.

3. Symfony

A highly professional, modular framework built with decoupled PHP components. It is widely used for enterprise-level applications due to its stability and configurability.


Question 9

9. Dynamic Database Insertion & Secure Form Integration (3+5 Marks)

a) The Process of Data Insertion from PHP to MySQL

To safely insert dynamic web data into a relational database, you must follow these steps:

  1. Initialize Connection: Create a persistent database connection (such as PDO or MySQLi) from PHP to the target database server.
  2. Retrieve & Sanitize Input: Fetch data from the HTTP request (e.g., using the $_POST superglobal) and validate or sanitize it to ensure it matches the expected format.
  3. Prepare SQL Statement: Compile an INSERT INTO statement with parameter placeholders (rather than direct string concatenation) to prevent SQL injection.
  4. Bind Parameters & Execute: Bind the sanitized inputs to the pre-compiled parameters and execute the query on the database server.
  5. Verify Status: Confirm if the database write was successful and display a clean status message to the user.

b) Secure Form Data Insertion Code (Object-Oriented MySQLi with Prepared Statements)

This script securely processes incoming form data submitted via the POST method and writes it to a MySQL database using the MySQLi extension.

PHP Code: Secure MySQLi Insertion Handler
<?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();
?>

Question 10

10. CodeIgniter Helpers: Design, Types, & Loading Mechanisms (4+4 Marks)

a) Commonly Used CodeIgniter Helpers and Their Purposes

Definition — CodeIgniter Helpers Helpers are procedural collections of standalone utility functions in CodeIgniter. Unlike object-oriented libraries, helpers are not instantiated as classes; their functions can be called directly inside views, models, or controllers once loaded.
URL Helper

Provides functions to simplify generating links and routing redirects inside views.

base_url(), site_url(), anchor(), redirect()
Form Helper

Automates generating secure HTML form elements and retaining validated values.

form_open(), form_input(), form_close(), set_value()
Cookie Helper

Provides a clean interface for reading, writing, and deleting client-side cookies.

set_cookie(), get_cookie(), delete_cookie()
File Helper

Simplifies file system interactions like reading, writing, and listing directories.

read_file(), write_file(), get_filenames()

b) Loading Helpers in CodeIgniter

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.

Example: Loading Helpers in CodeIgniter 3 vs. 4
// 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']);
High-Yield Exam Core Points

Most Important Exam Points

Key takeaways and common student traps to keep in mind for descriptive questions.

Security & Scope Rules

  • Use static to preserve variables across calls
  • Pass by reference using & inside the function
  • HTTPS uses secure port 443; HTTP uses port 80
  • Superglobals are accessible in all scopes
  • MySQL triggers run automatically on table updates

API & Import Comparisons

  • PDO supports multiple DB types; MySQLi is MySQL only
  • Use isset() to safely verify variables
  • array_push() appends items to end of array
  • PHP fopen with "r" is for read-only access
  • Always check database errors with connect_error
Quick Revision Matrix

Last-Minute Revision Sheet

Variable Scopes

  • Local: inside function scope
  • Global: declared outside
  • Static: retains state
  • Use global keyword to access

Loops & Logic

  • FOR: structured iteration
  • FOREACH: traverses arrays
  • ===: strict type identity
  • ==: loose type evaluation

State Handling

  • Cookie: stored in client browser
  • Session: stored securely on server
  • Unset Session: session_unset()
  • Delete Cookie: set time to past

Helpers & MVC

  • Helpers: standalone functions
  • Model: manages data and schemas
  • View: displays HTML presentation
  • Controller: coordinates requests

Web Designing Past Paper Solutions · Hand-crafted Exam Notes · Aligned with June 2024 Syllabus Guidelines.