CST463 Web Programming - Solved Papers

CST463 Web Programming - Answer Key

CST463 Web Programming - Answer Key

CST463 Web Programming - Answer Key

December 2022 Examination (2019 Scheme)

Institution: APJ Abdul Kalam Technological University
Subject: Web Programming (CST463)
Examination: Seventh Semester B.Tech Degree Examination December 2022
Max. Marks: 100
Duration: 3 Hours
Question Paper Code: 1000CST463122202


PART A (Short Answer Questions)

Instructions: Answer all questions, each carries 3 marks.


Question 1 (3 marks)

Why do you call MIME as an extension feature? Justify with suitable statements.

Answer:

MIME (Multipurpose Internet Mail Extensions) is called an extension feature because it extends the original email protocol (SMTP) to support non-ASCII content types. Originally, email systems could only handle plain ASCII text, but MIME added the capability to include multimedia content such as images, audio, video, and application-specific data.

Key Points:

  • Extension of SMTP: MIME extends the Simple Mail Transfer Protocol to support various content types beyond plain text
  • Content Type Specification: Uses Content-Type headers to identify the type of data being transmitted
  • Backward Compatibility: Works as an extension without breaking existing email systems
  • Multimedia Support: Enables transmission of binary data, attachments, and formatted content

Example MIME Types:

  • text/html - HTML documents
  • image/jpeg - JPEG images
  • application/pdf - PDF documents
  • video/mp4 - MP4 video files

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 1 - MARK DISTRIBUTION (Total: 3 marks)            │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Definition and explanation of MIME as      │ 1.5 marks  │
│    extension feature                           │            │
│    - Extension of SMTP concept                 │            │
│    - Why it's called "extension"               │            │
│    - Backward compatibility                    │            │
│                                                │            │
│ 2. Supporting examples and justification       │ 1.5 marks  │
│    - Multimedia support capabilities           │            │
│    - Content-Type specification                │            │
│    - Practical MIME type examples              │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Definition + Explanation with Examples (Section 1.2, Pattern 2)

Question 2 (3 marks)

Discuss URI's and URL.

Answer:

URI (Uniform Resource Identifier): A URI is a string of characters that uniquely identifies a resource on the internet or within any system. It is a general concept that includes both URLs and URNs (Uniform Resource Names).

URL (Uniform Resource Locator): A URL is a specific type of URI that not only identifies a resource but also provides the means to locate it by specifying its network location and access mechanism.

Key Differences:

  • URI: General identifier for any resource (broader concept)
  • URL: Specifies location and access method (subset of URI)
  • Relationship: All URLs are URIs, but not all URIs are URLs

Examples:

  • URL: https://www.example.com/page.html (specifies protocol and location)
  • URI: mailto:user@example.com (identifies a resource)
  • URN: urn:isbn:0-486-27557-4 (names a resource without location)

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 2 - MARK DISTRIBUTION (Total: 3 marks)            │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. URI (Uniform Resource Identifier)          │ 1.5 marks  │
│    - Definition and concept                    │            │
│    - General identifier characteristics        │            │
│    - URI examples                              │            │
│                                                │            │
│ 2. URL (Uniform Resource Locator)             │ 1.5 marks  │
│    - Definition and concept                    │            │
│    - Location and access method specification  │            │
│    - Relationship with URI                     │            │
│    - URL examples and comparison               │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Differentiate Two Concepts (Section 1.2, Pattern 1)

Question 3 (3 marks)

Compare Absolute Positioning and Relative positioning.

Answer:

Absolute Positioning and Relative Positioning are CSS positioning schemes that control how elements are placed on a webpage.

Comparison:

Aspect Absolute Positioning Relative Positioning
Position Reference Positioned relative to the nearest positioned ancestor or viewport Positioned relative to its normal position in document flow
Document Flow Removed from normal document flow Remains in normal document flow
Space Occupation Does not occupy space; other elements ignore it Occupies original space; other elements flow normally
CSS Property position: absolute; position: relative;
Common Use Overlays, popups, dropdown menus Fine-tuning element position without disrupting layout

Example:

/* Relative Positioning */
.relative-box {
    position: relative;
    top: 10px;
    left: 20px;
}

/* Absolute Positioning */
.absolute-box {
    position: absolute;
    top: 50px;
    right: 30px;
}

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 3 - MARK DISTRIBUTION (Total: 3 marks)            │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Absolute Positioning                        │ 1.5 marks  │
│    - Definition and characteristics            │            │
│    - Position reference (ancestor/viewport)    │            │
│    - Document flow behavior                    │            │
│    - Common use cases                          │            │
│    - CSS syntax example                        │            │
│                                                │            │
│ 2. Relative Positioning                        │ 1.5 marks  │
│    - Definition and characteristics            │            │
│    - Position reference (normal position)      │            │
│    - Document flow behavior                    │            │
│    - Common use cases                          │            │
│    - CSS syntax example                        │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Differentiate Two Concepts (Section 1.2, Pattern 1)

Question 4 (3 marks)

What is a call back function in JavaScript? State how it is different from normal functions.

Answer:

A callback function is a function passed as an argument to another function, which is then invoked inside the outer function to complete some action or operation. Callbacks enable asynchronous programming and event-driven behavior in JavaScript.

Key Points:

  • Passed as Argument: Callback functions are passed as parameters to other functions
  • Asynchronous Execution: Often used for operations that take time (AJAX, timers, event handlers)
  • Invoked by Caller: The receiving function decides when and how to call the callback

Differences from Normal Functions:

Aspect Normal Function Callback Function
Invocation Called directly by the programmer Called by another function
Purpose Executes immediately when called Executes at a specific event or time
Usage Standard function calls Event handlers, async operations, array methods

Example:

// Normal function
function greet() {
    console.log("Hello!");
}
greet(); // Called directly

// Callback function example
function calculate(a, b, callback) {
    let result = a + b;
    callback(result); // Calls the callback with result
}

// Pass function as callback
calculate(5, 3, function(answer) {
    console.log("Sum is: " + answer); // Output: Sum is: 8
});

// Real-world callback example with setTimeout
setTimeout(function() {
    console.log("This runs after 2 seconds");
}, 2000);

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 4 - MARK DISTRIBUTION (Total: 3 marks)            │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Callback Function Definition and Concept   │ 1.5 marks  │
│    - Definition of callback function           │            │
│    - Function passed as argument               │            │
│    - Asynchronous execution capability         │            │
│    - Event-driven behavior                     │            │
│                                                │            │
│ 2. Differences from Normal Functions          │ 1.5 marks  │
│    - Invocation method comparison              │            │
│    - Purpose and execution timing              │            │
│    - Usage scenarios and examples              │            │
│    - Code examples demonstrating differences   │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Definition + Explanation with Comparison (Section 1.2, Pattern 2)

Question 5 (3 marks)

Write a PHP program to check whether the given number is prime or not.

Answer:

Approach: A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. We check divisibility from 2 to the square root of the number.

Implementation:

<?php
function isPrime($n) {
    if ($n <= 1) return false;
    if ($n == 2) return true;
    if ($n % 2 == 0) return false;

    for ($i = 3; $i <= sqrt($n); $i += 2) {
        if ($n % $i == 0) return false;
    }
    return true;
}

// Test the function
$number = 17;
if (isPrime($number)) {
    echo "$number is a prime number";
} else {
    echo "$number is not a prime number";
}
?>

Explanation:
The function first handles edge cases (numbers ≤ 1 are not prime, 2 is prime, even numbers are not prime). Then it checks divisibility from 3 to √n, skipping even numbers. If no divisor is found, the number is prime.

Test Cases:

  • Input: 17 → Output: "17 is a prime number"
  • Input: 10 → Output: "10 is not a prime number"

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 5 - MARK DISTRIBUTION (Total: 3 marks)            │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Complete PHP Prime Number Program           │ 3 marks    │
│    - Function definition with parameter        │            │
│    - Edge case handling (n<=1, n==2, even)     │            │
│    - Prime checking logic (loop to sqrt(n))    │            │
│    - Optimization (checking only odd numbers)  │            │
│    - Test implementation and output            │            │
│    - Code explanation and test cases           │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Complete Program (Section 1.2, Pattern 5)

Question 6 (3 marks)

List out the sorting functions for Arrays in PHP. Illustrate with suitable examples.

Answer:

PHP provides several built-in functions to sort arrays in different ways:

Key Sorting Functions:

  1. sort() - Sorts array in ascending order (reindexes keys)
  2. rsort() - Sorts array in descending order (reindexes keys)
  3. asort() - Sorts associative array in ascending order by value (maintains key association)
  4. arsort() - Sorts associative array in descending order by value (maintains key association)
  5. ksort() - Sorts array by key in ascending order
  6. krsort() - Sorts array by key in descending order

Examples:

<?php
// Indexed array sorting
$numbers = array(5, 2, 8, 1, 9);
sort($numbers); // [1, 2, 5, 8, 9]

// Associative array sorting by value
$students = array("John" => 85, "Alice" => 92, "Bob" => 78);
asort($students); // ["Bob" => 78, "John" => 85, "Alice" => 92]

// Associative array sorting by key
$marks = array("Math" => 85, "English" => 90, "Science" => 78);
ksort($marks); // ["English" => 90, "Math" => 85, "Science" => 78]
?>

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 6 - MARK DISTRIBUTION (Total: 3 marks)            │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. List of PHP Array Sorting Functions        │ 2 marks    │
│    - sort() and rsort()                        │            │
│    - asort() and arsort()                      │            │
│    - ksort() and krsort()                      │            │
│    - Brief explanation of each function        │            │
│                                                │            │
│ 2. Practical Examples with Code               │ 1 mark     │
│    - Indexed array sorting example             │            │
│    - Associative array by value example        │            │
│    - Associative array by key example          │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Explanation + Examples (Section 1.2, Pattern 3)

Question 7 (3 marks)

Discuss the various steps for establishing PHP-MySQL connection with a MySQL database.

Answer:

Establishing a PHP-MySQL connection using PDO (PHP Data Objects) involves the following steps:

Steps for Connection:

  1. Define Connection Parameters:

    • Database host (usually "localhost")
    • Database name
    • Username and password
    • Character set (utf8mb4 recommended)
  2. Create DSN (Data Source Name):

    • Format: "mysql:host=hostname;dbname=database_name;charset=utf8mb4"
  3. Set PDO Options:

    • Error mode (ERRMODE_EXCEPTION for exception handling)
    • Fetch mode (FETCH_ASSOC for associative arrays)
    • Emulated prepares (false for real prepared statements)
  4. Establish Connection:

    • Create PDO object with DSN, username, password, and options
    • Wrap in try-catch block for error handling

Example:

<?php
try {
    // Step 1: Define connection parameters
    $host = "localhost";
    $dbname = "test_db";
    $username = "root";
    $password = "";

    // Step 2: Create DSN
    $dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4";

    // Step 3: Set options
    $options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ];

    // Step 4: Create connection
    $pdo = new PDO($dsn, $username, $password, $options);
    echo "Connection successful!";

} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}
?>

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 7 - MARK DISTRIBUTION (Total: 3 marks)            │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Steps for Establishing Connection          │ 2 marks    │
│    - Define connection parameters              │            │
│    - Create DSN (Data Source Name)             │            │
│    - Set PDO options                           │            │
│    - Establish connection with try-catch       │            │
│                                                │            │
│ 2. Complete Working Code Example               │ 1 mark     │
│    - Full PHP PDO connection script            │            │
│    - Error handling implementation             │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Explanation + Example (Section 1.2, Pattern 3)

Question 8 (3 marks)

Illustrate with a sample PHP script, how CREATE operations on MySQL table are implemented in PHP.

Answer:

CREATE operations in PHP-MySQL involve creating database tables using DDL (Data Definition Language) statements. The CREATE TABLE statement is executed through PDO.

Implementation:

<?php
try {
    // Establish PDO connection
    $dsn = "mysql:host=localhost;dbname=college_db;charset=utf8mb4";
    $pdo = new PDO($dsn, "root", "", [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);

    // CREATE TABLE SQL statement
    $sql = "CREATE TABLE IF NOT EXISTS students (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        email VARCHAR(100) UNIQUE NOT NULL,
        age INT,
        course VARCHAR(50),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )";

    // Execute the CREATE statement
    $pdo->exec($sql);
    echo "Table 'students' created successfully!";

} catch (PDOException $e) {
    die("Error creating table: " . $e->getMessage());
}
?>

Key Points:

  • Use exec() method for DDL statements (no prepared statements needed)
  • IF NOT EXISTS clause prevents errors if table already exists
  • Define appropriate data types and constraints (PRIMARY KEY, UNIQUE, NOT NULL)
  • Always use try-catch for error handling

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 8 - MARK DISTRIBUTION (Total: 3 marks)            │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Complete CREATE TABLE Program               │ 3 marks    │
│    - PDO connection establishment              │            │
│    - CREATE TABLE SQL statement                │            │
│    - Table structure with constraints          │            │
│    - exec() method for DDL execution           │            │
│    - Try-catch error handling                  │            │
│    - Key points explanation                    │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Complete Program (Section 1.2, Pattern 5)

Question 9 (3 marks)

Describe the schema of a document implemented in JSON with suitable examples.

Answer:

A JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. It defines the structure, data types, required fields, and constraints for JSON data.

Key Components of JSON Schema:

  • $schema: Specifies the JSON Schema version
  • type: Defines the data type (object, array, string, number, boolean, null)
  • properties: Defines the properties of an object
  • required: Lists mandatory fields
  • additionalProperties: Controls whether extra properties are allowed

Example JSON Document:

{
    "studentId": 101,
    "name": "John Doe",
    "email": "john@example.com",
    "age": 21,
    "courses": ["Web Programming", "Data Structures"]
}

Corresponding JSON Schema:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {
        "studentId": {
            "type": "integer",
            "minimum": 1
        },
        "name": {
            "type": "string",
            "minLength": 1
        },
        "email": {
            "type": "string",
            "format": "email"
        },
        "age": {
            "type": "integer",
            "minimum": 18,
            "maximum": 100
        },
        "courses": {
            "type": "array",
            "items": {
                "type": "string"
            }
        }
    },
    "required": ["studentId", "name", "email"],
    "additionalProperties": false
}

Benefits: Ensures data validation, documentation, and consistency across systems.

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 9 - MARK DISTRIBUTION (Total: 3 marks)            │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. JSON Schema Explanation                    │ 2 marks    │
│    - Definition and purpose                    │            │
│    - Key components ($schema, type, etc.)      │            │
│    - Structure and validation capabilities     │            │
│    - Benefits of using JSON Schema             │            │
│                                                │            │
│ 2. Practical Examples                          │ 1 mark     │
│    - Example JSON document                     │            │
│    - Corresponding JSON Schema                 │            │
│    - Properties and constraints demonstration  │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Explanation + Examples (Section 1.2, Pattern 3)

Question 10 (3 marks)

Explain the role of Resource controllers in Laravel.

Answer:

Resource Controllers in Laravel provide a convenient way to build RESTful controllers that handle CRUD (Create, Read, Update, Delete) operations with minimal code. They automatically create methods for standard resource operations.

Key Points:

  • Automatic Method Generation: Creates seven standard methods for RESTful operations
  • Route Simplification: Single route declaration handles all CRUD routes
  • Convention over Configuration: Follows Laravel naming conventions automatically
  • RESTful Architecture: Implements REST principles out of the box

Seven Standard Methods:

Method Route Action Purpose
index() GET /resource index Display all resources
create() GET /resource/create create Show form to create new resource
store() POST /resource store Store new resource
show() GET /resource/{id} show Display specific resource
edit() GET /resource/{id}/edit edit Show form to edit resource
update() PUT/PATCH /resource/{id} update Update specific resource
destroy() DELETE /resource/{id} destroy Delete specific resource

Example:

// Create resource controller
php artisan make:controller StudentController --resource

// routes/web.php - Single line registers all routes
Route::resource('students', StudentController::class);

This automatically creates routes for all seven methods, following RESTful conventions.

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 10 - MARK DISTRIBUTION (Total: 3 marks)           │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Resource Controllers Explanation            │ 2 marks    │
│    - Definition and role                       │            │
│    - Key features and benefits                 │            │
│    - Seven standard RESTful methods            │            │
│    - Route simplification capabilities         │            │
│                                                │            │
│ 2. Practical Example with Syntax              │ 1 mark     │
│    - Controller creation command               │            │
│    - Route registration example                │            │
│    - RESTful conventions demonstration         │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Explanation + Example (Section 1.2, Pattern 3)

PART B (Long Answer Questions)

Instructions: Answer any one full question from each module, each carries 14 marks.


Module I — Module I
Question 11 (14 marks)

a) Write the equivalent HTML code to implement the following in a web page: (4 marks)

  1. An image titled "flower.jpg" with proper attribute to set height, width and message text.
  2. Unordered list with values tea, coffee and milk

Answer:

Implementation:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image and List Example</title>
</head>
<body>
    <!-- 1) Image with proper attributes -->
    <img src="flower.jpg"
         alt="Beautiful Flower"
         title="This is a flower image"
         width="300"
         height="400">

    <!-- 2) Unordered list with beverages -->
    <ul>
        <li>tea</li>
        <li>coffee</li>
        <li>milk</li>
    </ul>
</body>
</html>

Explanation:

  • Image Attributes:
    • src: Specifies the image file path
    • alt: Provides alternative text for accessibility and when image cannot be displayed
    • title: Message text that appears as tooltip on hover
    • width and height: Set dimensions in pixels
  • Unordered List:
    • <ul> creates bullet-point list
    • Each <li> represents a list item

Mark Distribution (Part a):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 11(a) - MARK DISTRIBUTION (Total: 4 marks)        │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Image Implementation                        │ 2 marks    │
│    - <img> tag with src attribute              │            │
│    - alt and title attributes                  │            │
│    - width and height attributes               │            │
│    - Proper HTML structure                     │            │
│                                                │            │
│ 2. Unordered List Implementation               │ 2 marks    │
│    - <ul> tag structure                        │            │
│    - Three <li> items (tea, coffee, milk)      │            │
│    - Complete HTML structure                   │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Two Equal Components (Section 2.2, Pattern 4)

b) Explain following html tags with proper example. (10 marks)

  1. <textarea> 2. <span> 3. <tr> 4. <form> 5. <a>

Answer:

1. <textarea> Tag

Definition: The <textarea> tag defines a multi-line text input control, commonly used in forms for collecting larger amounts of text like comments, reviews, or messages.

Key Attributes:

  • rows: Specifies visible number of lines
  • cols: Specifies visible width in characters
  • name: Name for form submission
  • placeholder: Hint text displayed when empty
  • required: Makes the field mandatory
  • maxlength: Limits character count
  • readonly: Makes field non-editable
  • disabled: Disables the field

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Textarea Example</title>
</head>
<body>
    <h2>Feedback Form</h2>
    <form>
        <label for="comments">Your Comments:</label><br>
        <textarea id="comments"
                  name="user_comments"
                  rows="5"
                  cols="50"
                  placeholder="Enter your feedback here..."
                  maxlength="500"
                  required>
        </textarea><br>
        <small>Maximum 500 characters</small><br>
        <button type="submit">Submit</button>
    </form>
</body>
</html>

Use Cases: Comments sections, message boxes, feedback forms, description fields


2. <span> Tag

Definition: The <span> tag is an inline container used to group inline elements and apply styles or JavaScript to specific portions of text without breaking the flow.

Key Characteristics:

  • Inline element: Does not start on a new line
  • No semantic meaning: Pure container for styling
  • CSS target: Used to apply styles to specific text portions
  • JavaScript manipulation: Can be selected and modified via scripts

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Span Example</title>
</head>
<body>
    <h2>Product Information</h2>
    <p>
        This <span class="highlight">amazing product</span> is available at
        <span class="price">$29.99</span> only!
    </p>

    <p>
        Please note: <span class="error-text">Stock is limited</span>
    </p>

    <p>
        The word <span style="color: blue; text-decoration: underline;">important</span>
        is emphasized.
    </p>
</body>
</html>

Use Cases: Styling specific text portions, applying JavaScript to text segments, inline formatting


3. <tr> Tag

Definition: The <tr> (table row) tag defines a row in an HTML table. It must be used within a <table> element and contains <th> (header cells) or <td> (data cells).

Key Characteristics:

  • Container for cells: Must contain <th> or <td> elements
  • Table structure: Defines horizontal rows
  • Styling target: Can be styled independently for zebra striping or hover effects

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Table Row Example</title>
</head>
<body>
    <h2>Student Information</h2>
    <table border="1">
        <thead>
            <tr>
                <th>Roll No</th>
                <th>Name</th>
                <th>Course</th>
                <th>Grade</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>101</td>
                <td>John Doe</td>
                <td>Web Programming</td>
                <td>A</td>
            </tr>
            <tr>
                <td>102</td>
                <td>Alice Smith</td>
                <td>Data Structures</td>
                <td>A+</td>
            </tr>
            <tr>
                <td>103</td>
                <td>Bob Johnson</td>
                <td>Database Systems</td>
                <td>B+</td>
            </tr>
        </tbody>
    </table>
</body>
</html>

Use Cases: Creating data tables, displaying structured information, pricing tables, schedules


4. <form> Tag

Definition: The <form> tag creates an HTML form for user input. Forms are used to collect data from users and submit it to a server for processing.

Key Attributes:

  • action: URL where form data is sent
  • method: HTTP method (GET or POST)
  • enctype: Encoding type for form data (especially for file uploads)
  • name: Name of the form
  • target: Where to display response (_self, _blank, etc.)
  • autocomplete: Enable/disable autocomplete
  • novalidate: Disable HTML5 validation

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form Example</title>
</head>
<body>
    <h2>Student Registration</h2>
    <form action="process.php" method="POST">
        <label for="name">Full Name:</label><br>
        <input type="text" id="name" name="student_name" required><br><br>

        <label for="email">Email:</label><br>
        <input type="email" id="email" name="student_email" required><br><br>

        <label for="password">Password:</label><br>
        <input type="password" id="password" name="password" required minlength="6"><br><br>

        <label for="course">Select Course:</label><br>
        <select id="course" name="course" required>
            <option value="">-- Choose Course --</option>
            <option value="cst463">Web Programming</option>
            <option value="cst301">Data Structures</option>
            <option value="cst302">Database Systems</option>
        </select><br><br>

        <label>
            <input type="checkbox" name="terms" required>
            I agree to terms and conditions
        </label><br><br>

        <button type="submit">Register</button>
        <button type="reset">Clear Form</button>
    </form>
</body>
</html>

Common Form Input Types:

  • text, email, password, number, tel, url
  • checkbox, radio, select, textarea
  • date, time, file, submit, reset, button

Use Cases: Login forms, registration forms, contact forms, search boxes, surveys


5. <a> Tag

Definition: The <a> (anchor) tag defines a hyperlink that links one page to another or to a specific location within the same page. It is one of the most fundamental elements of the web.

Key Attributes:

  • href: Destination URL (required)
  • target: Where to open the link (_self, _blank, _parent, _top)
  • title: Tooltip text on hover
  • download: Prompts download instead of navigation
  • rel: Relationship between current and linked document
  • type: MIME type of linked resource

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Anchor Tag Example</title>
</head>
<body>
    <h1>Different Types of Links</h1>

    <h3>1. External Link</h3>
    <p>
        Visit
        <a href="https://www.example.com" target="_blank" rel="noopener noreferrer">
            Example Website
        </a>
        to learn more. Opens in new tab.
    </p>

    <h3>2. Internal Page Link</h3>
    <p>
        Go to our
        <a href="about.html" title="Learn more about us">About Page</a>
    </p>

    <h3>3. Email Link</h3>
    <p>
        Contact us at
        <a href="mailto:info@example.com?subject=Inquiry&body=Hello">
            info@example.com
        </a>
    </p>

    <h3>4. Phone Link</h3>
    <p>
        Call us:
        <a href="tel:+919876543210">+91 98765 43210</a>
    </p>

    <h3>5. Anchor Link (Same Page)</h3>
    <p>
        Jump to
        <a href="#section-bottom">bottom of page</a>
    </p>

    <h3>6. Download Link</h3>
    <p>
        <a href="document.pdf" download="MyDocument.pdf">
            Download PDF Document
        </a>
    </p>

    <br><br><br><br><br><br>

    <div id="section-bottom">
        <h3>Bottom Section</h3>
        <p>You scrolled here using anchor link!</p>
        <p><a href="#top">Back to Top</a></p>
    </div>
</body>
</html>

Link Types:

  • Absolute URLs: Full web addresses (https://www.example.com)
  • Relative URLs: Links within same website (about.html, ../contact.html)
  • Anchor Links: Jump to page sections (#section-id)
  • Protocol Links: Email (mailto:), phone (tel:), etc.

Use Cases: Navigation menus, hyperlinks in content, downloadable resources, email/phone contacts

Mark Distribution (Part b):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 11(b) - MARK DISTRIBUTION (Total: 10 marks)       │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. <textarea> Tag Explanation                  │ 2 marks    │
│    - Definition and purpose                    │            │
│    - Key attributes (rows, cols, name, etc.)   │            │
│    - Complete working example                  │            │
│    - Use cases                                 │            │
│                                                │            │
│ 2. <span> Tag Explanation                      │ 2 marks    │
│    - Definition and characteristics            │            │
│    - Inline element properties                 │            │
│    - Complete working example                  │            │
│    - Use cases                                 │            │
│                                                │            │
│ 3. <tr> Tag Explanation                        │ 2 marks    │
│    - Definition and purpose                    │            │
│    - Table row characteristics                 │            │
│    - Complete working example                  │            │
│    - Use cases                                 │            │
│                                                │            │
│ 4. <form> Tag Explanation                      │ 2 marks    │
│    - Definition and purpose                    │            │
│    - Key attributes (action, method, etc.)     │            │
│    - Complete working example                  │            │
│    - Use cases                                 │            │
│                                                │            │
│ 5. <a> Tag Explanation                         │ 2 marks    │
│    - Definition and purpose                    │            │
│    - Key attributes (href, target, etc.)       │            │
│    - Complete working example                  │            │
│    - Different link types                      │            │
│    - Use cases                                 │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Five Equal Components (Section 2.2, Pattern 2 adapted)
Total: 4 marks (Part a) + 10 marks (Part b) = 14 marks

Question 12 (14 marks)

a) Design a webpage that displays the following table. (8 marks)

Company Model
Dodge Challenger
Maruti Swift
Jeep Wrangler
Ford Fusion, Fiesta, Escape
BMW BMW 5 Series

Answer:

Overview: This solution creates a well-structured HTML table displaying car companies and their models with professional styling.

Implementation:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Car Companies and Models</title>
</head>
<body>
    <h1>Car Companies and Models</h1>

    <table border="1">
        <thead>
            <tr>
                <th>Company</th>
                <th>Model</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Dodge</td>
                <td>Challenger</td>
            </tr>
            <tr>
                <td>Maruti</td>
                <td>Swift</td>
            </tr>
            <tr>
                <td>Jeep</td>
                <td>Wrangler</td>
            </tr>
            <tr>
                <td rowspan="3">Ford</td>
                <td>Fusion</td>
            </tr>
            <tr>
                <td>Fiesta</td>
            </tr>
            <tr>
                <td>Escape</td>
            </tr>
            <tr>
                <td>BMW</td>
                <td>BMW 5 Series</td>
            </tr>
        </tbody>
    </table>
</body>
</html>

Explanation:

  1. HTML Structure:

    • Complete DOCTYPE declaration for HTML5
    • Semantic table structure with <thead> and <tbody>
    • Proper use of <th> for headers and <td> for data cells
    • rowspan="3" attribute used for Ford company to span three rows for its three models
    • border="1" attribute added to table for basic border display
  2. Key Features:

    • Clean, semantic HTML5 structure
    • Proper table organization with thead and tbody sections
    • Accessibility considerations with proper headers
    • Rowspan attribute demonstrates table cell spanning

Alternative Simpler Version (if rowspan not used):

<tr>
    <td class="company-column">Ford</td>
    <td class="model-column">Fusion, Fiesta, Escape</td>
</tr>

Mark Distribution (Part a):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 12(a) - MARK DISTRIBUTION (Total: 8 marks)        │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Complete HTML Table Implementation          │ 8 marks    │
│    - Proper HTML5 structure (DOCTYPE, etc.)    │            │
│    - Table structure (<table>, <thead>, etc.)  │            │
│    - Table headers (<th> for Company, Model)   │            │
│    - Table body with data rows (<tbody>, <tr>) │            │
│    - Data cells with company and model info    │            │
│    - Rowspan attribute for Ford (3 models)     │            │
│    - All 5 companies correctly displayed       │            │
│    - Border and formatting                     │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Complete HTML Program (Section 3.2, Pattern 3)

b) Write down the general format of an HTTP request and an HTTP response. What is the purpose of the following HTTP headers? Also, identify whether they are included with an HTTP header/response or both. (6 marks)
i. host
ii. last-modified

Answer:

HTTP Request Format

An HTTP request consists of three main parts:

Structure:

Request-Line
Headers
[Empty Line]
[Message Body]

Detailed Format:

METHOD /path/to/resource HTTP/1.1
Header-Name: Header-Value
Another-Header: Another-Value

[Optional Request Body for POST/PUT]

Example HTTP Request:

GET /index.html HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
Accept: text/html,application/xhtml+xml
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Cookie: session_id=abc123xyz

Request Components:

  1. Request Line:

    • HTTP Method (GET, POST, PUT, DELETE, etc.)
    • Request URI (path to resource)
    • HTTP Version (HTTP/1.1, HTTP/2)
  2. Request Headers:

    • Host, User-Agent, Accept, Accept-Language, etc.
    • Provide additional information about the request
  3. Empty Line: Separates headers from body

  4. Message Body: (optional)

    • Contains data for POST/PUT requests
    • Empty for GET requests

HTTP Response Format

An HTTP response also consists of three main parts:

Structure:

Status-Line
Headers
[Empty Line]
[Message Body]

Detailed Format:

HTTP/1.1 STATUS-CODE Reason-Phrase
Header-Name: Header-Value
Another-Header: Another-Value

[Response Body - HTML, JSON, etc.]

Example HTTP Response:

HTTP/1.1 200 OK
Date: Mon, 13 Nov 2025 10:30:00 GMT
Server: Apache/2.4.41 (Ubuntu)
Last-Modified: Sat, 11 Nov 2025 08:15:00 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 1234
Connection: keep-alive
Cache-Control: max-age=3600

<!DOCTYPE html>
<html>
<head><title>Example Page</title></head>
<body><h1>Hello World!</h1></body>
</html>

Response Components:

  1. Status Line:

    • HTTP Version (HTTP/1.1)
    • Status Code (200, 404, 500, etc.)
    • Reason Phrase (OK, Not Found, Internal Server Error)
  2. Response Headers:

    • Server, Content-Type, Content-Length, Last-Modified, etc.
    • Provide metadata about the response
  3. Empty Line: Separates headers from body

  4. Message Body:

    • Actual content (HTML, JSON, XML, images, etc.)
    • Contains the requested resource

HTTP Header Analysis

i. Host Header

Purpose: The Host header specifies the domain name of the server and optionally the TCP port number on which the server is listening. It is essential for virtual hosting, where multiple domains are hosted on a single IP address.

Type: REQUEST Header

Characteristics:

  • Mandatory in HTTP/1.1: Required in all HTTP/1.1 requests
  • Virtual Hosting Support: Allows one server to host multiple websites
  • Format: Host: hostname[:port]

Example:

Host: www.example.com
Host: www.example.com:8080
Host: localhost:3000

Use Case:
When a server hosts multiple websites (www.example1.com, www.example2.com) on the same IP address, the Host header tells the server which website the client wants to access.

Present in: HTTP REQUEST only


ii. Last-Modified Header

Purpose: The Last-Modified header indicates the date and time when the resource was last modified on the server. It is used for caching and conditional requests to determine if the cached version is still valid.

Type: RESPONSE Header

Characteristics:

  • Caching Mechanism: Helps browsers cache resources efficiently
  • Conditional Requests: Used with If-Modified-Since request header
  • Format: Last-Modified: Day, DD Mon YYYY HH:MM:SS GMT

Example:

Last-Modified: Sat, 11 Nov 2025 14:30:00 GMT

How It Works:

  1. First Request:

    GET /style.css HTTP/1.1
    Host: www.example.com

    Response:

    HTTP/1.1 200 OK
    Last-Modified: Sat, 11 Nov 2025 14:30:00 GMT
    Content-Type: text/css
    
    [CSS Content]
  2. Subsequent Request (Conditional):

    GET /style.css HTTP/1.1
    Host: www.example.com
    If-Modified-Since: Sat, 11 Nov 2025 14:30:00 GMT

    Response (if not modified):

    HTTP/1.1 304 Not Modified
    Last-Modified: Sat, 11 Nov 2025 14:30:00 GMT

    Response (if modified):

    HTTP/1.1 200 OK
    Last-Modified: Mon, 13 Nov 2025 09:00:00 GMT
    Content-Type: text/css
    
    [Updated CSS Content]

Benefits:

  • Reduces bandwidth by avoiding unnecessary downloads
  • Improves page load times through effective caching
  • Enables conditional GET requests

Present in: HTTP RESPONSE only


Summary Table:

Header Type Purpose Present In
Host Request Specifies target domain for virtual hosting REQUEST only
Last-Modified Response Indicates resource modification time for caching RESPONSE only

Mark Distribution (Part b):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 12(b) - MARK DISTRIBUTION (Total: 6 marks)        │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. HTTP Request and Response Formats           │ 3 marks    │
│    - HTTP Request format and structure         │            │
│    - Request components (line, headers, body)  │            │
│    - HTTP Response format and structure        │            │
│    - Response components (status, headers, body│            │
│    - Examples for both request and response    │            │
│                                                │            │
│ 2. Host Header Analysis (i)                    │ 1.5 marks  │
│    - Purpose and definition                    │            │
│    - Virtual hosting explanation               │            │
│    - Format and examples                       │            │
│    - Identification as REQUEST header          │            │
│                                                │            │
│ 3. Last-Modified Header Analysis (ii)          │ 1.5 marks  │
│    - Purpose and caching mechanism             │            │
│    - Format and examples                       │            │
│    - Conditional request workflow              │            │
│    - Identification as RESPONSE header         │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Three Components (Section 2.2, Pattern 2 adapted for 6 marks)
Total: 8 marks (Part a) + 6 marks (Part b) = 14 marks

Module II — Module II
Question 13 (14 marks)

a) Write CSS code for the following: (6 marks)
i) set the background color for the hover and active link states to "yellow".
ii) Set the list style for ordered lists to "lower case alphabet".
iii) Set "Boat.gif" as the background image of the page.
iv) Set dotted border for the document.

Answer:

Complete CSS Implementation:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Styling Example</title>
    <style>
        /* i) Set background color for hover and active link states to yellow */
        a:hover {
            background-color: yellow;
        }

        a:active {
            background-color: yellow;
        }

        /* ii) Set list style for ordered lists to lower case alphabet */
        ol {
            list-style-type: lower-alpha;
        }

        /* iii) Set "Boat.gif" as the background image of the page */
        body {
            background-image: url('Boat.gif');
            background-repeat: repeat;  /* Optional: controls tiling */
            background-size: auto;      /* Optional: controls size */
        }

        /* iv) Set dotted border for the document (body element) */
        body {
            border: 2px dotted black;
            padding: 20px;  /* Add padding so content doesn't touch border */
            margin: 10px;   /* Add margin for spacing */
        }
    </style>
</head>
<body>
    <h2>CSS Styling Demonstration</h2>

    <!-- Demonstration of hover and active link states -->
    <p>
        Visit this <a href="https://www.example.com">sample link</a> and notice
        the yellow background when you hover or click.
    </p>

    <!-- Demonstration of ordered list with lower-alpha style -->
    <h3>Course Topics:</h3>
    <ol>
        <li>Introduction to Web Development</li>
        <li>HTML5 Fundamentals</li>
        <li>CSS3 Styling</li>
        <li>JavaScript Programming</li>
        <li>PHP Backend Development</li>
    </ol>

    <p>The page has a dotted border and Boat.gif as background image.</p>
</body>
</html>

Explanation:

  1. Link Hover and Active States (i):

    • a:hover - Applies when mouse hovers over the link
    • a:active - Applies when link is being clicked (mouse button pressed)
    • Both set background-color: yellow
  2. Ordered List Style (ii):

    • list-style-type: lower-alpha produces lowercase letters (a, b, c, d...)
    • Other options: upper-alpha (A, B, C), lower-roman (i, ii, iii), decimal (1, 2, 3)
  3. Background Image (iii):

    • background-image: url('Boat.gif') sets the image
    • Can add background-repeat, background-position, background-size for control
    • background-repeat: no-repeat prevents tiling if desired
  4. Dotted Border (iv):

    • border: 2px dotted black creates dotted border around body
    • Format: border: width style color
    • Other border styles: solid, dashed, double, groove, ridge, inset, outset

CSS-Only Version (Without HTML):

/* i) Hover and active link states with yellow background */
a:hover, a:active {
    background-color: yellow;
}

/* ii) Ordered lists with lowercase alphabet */
ol {
    list-style-type: lower-alpha;
}

/* iii) Background image for the page */
body {
    background-image: url('Boat.gif');
}

/* iv) Dotted border for document */
body {
    border: 2px dotted black;
}

Mark Distribution (Part a):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 13(a) - MARK DISTRIBUTION (Total: 6 marks)        │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Link Hover and Active States (i)           │ 1.5 marks  │
│    - a:hover with yellow background            │            │
│    - a:active with yellow background           │            │
│                                                │            │
│ 2. Ordered List Style (ii)                     │ 1.5 marks  │
│    - ol with list-style-type: lower-alpha      │            │
│                                                │            │
│ 3. Background Image (iii)                      │ 1.5 marks  │
│    - body with background-image: url('Boat.gif│            │
│    - Proper CSS syntax                         │            │
│                                                │            │
│ 4. Dotted Border (iv)                          │ 1.5 marks  │
│    - body with border: dotted                  │            │
│    - Correct border syntax                     │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Four Equal Sub-parts (Section 2.2, Pattern 3 adapted)

b) Discuss various types of control statements in JavaScript (8 marks)

Answer:

Definition: Control statements in JavaScript are used to control the flow of program execution based on conditions or to repeat code blocks multiple times. They enable decision-making and iteration in programs.


1. Conditional Statements

Conditional statements execute different blocks of code based on specified conditions.

a) if Statement

Executes a block of code if a specified condition is true.

Syntax:

if (condition) {
    // code to execute if condition is true
}

Example:

let age = 20;
if (age >= 18) {
    console.log("You are eligible to vote");
}
// Output: You are eligible to vote

b) if...else Statement

Provides an alternative block of code if the condition is false.

Syntax:

if (condition) {
    // code if condition is true
} else {
    // code if condition is false
}

Example:

let temperature = 15;
if (temperature > 25) {
    console.log("It's hot outside");
} else {
    console.log("It's cool outside");
}
// Output: It's cool outside

c) if...else if...else Statement

Tests multiple conditions sequentially.

Syntax:

if (condition1) {
    // code if condition1 is true
} else if (condition2) {
    // code if condition2 is true
} else {
    // code if all conditions are false
}

Example:

let marks = 75;
if (marks >= 90) {
    console.log("Grade: A");
} else if (marks >= 80) {
    console.log("Grade: B");
} else if (marks >= 70) {
    console.log("Grade: C");
} else {
    console.log("Grade: D");
}
// Output: Grade: C

d) switch Statement

Evaluates an expression and executes code blocks based on matching cases.

Syntax:

switch (expression) {
    case value1:
        // code block
        break;
    case value2:
        // code block
        break;
    default:
        // default code block
}

Example:

let day = 3;
let dayName;
switch (day) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    case 4:
        dayName = "Thursday";
        break;
    case 5:
        dayName = "Friday";
        break;
    default:
        dayName = "Weekend";
}
console.log(dayName);
// Output: Wednesday

2. Loop Statements

Loop statements repeatedly execute a block of code while a condition is true or for a specific number of iterations.

a) for Loop

Repeats a block of code a specific number of times.

Syntax:

for (initialization; condition; increment) {
    // code to be executed
}

Example:

for (let i = 1; i <= 5; i++) {
    console.log("Count: " + i);
}
// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5

b) while Loop

Executes code as long as a specified condition is true.

Syntax:

while (condition) {
    // code to be executed
}

Example:

let count = 1;
while (count <= 5) {
    console.log("Number: " + count);
    count++;
}
// Output:
// Number: 1
// Number: 2
// Number: 3
// Number: 4
// Number: 5

c) do...while Loop

Executes code at least once, then repeats as long as condition is true.

Syntax:

do {
    // code to be executed
} while (condition);

Example:

let num = 1;
do {
    console.log("Value: " + num);
    num++;
} while (num <= 3);
// Output:
// Value: 1
// Value: 2
// Value: 3

Difference from while: The do...while loop executes the code block once before checking the condition, guaranteeing at least one execution.

d) for...in Loop

Iterates over properties of an object.

Syntax:

for (variable in object) {
    // code to be executed
}

Example:

let student = {name: "John", age: 20, course: "CST463"};
for (let key in student) {
    console.log(key + ": " + student[key]);
}
// Output:
// name: John
// age: 20
// course: CST463

e) for...of Loop

Iterates over iterable objects (arrays, strings, etc.).

Syntax:

for (variable of iterable) {
    // code to be executed
}

Example:

let courses = ["HTML", "CSS", "JavaScript", "PHP"];
for (let course of courses) {
    console.log(course);
}
// Output:
// HTML
// CSS
// JavaScript
// PHP

3. Jump Statements

Jump statements alter the normal flow of execution.

a) break Statement

Exits a loop or switch statement prematurely.

Example:

for (let i = 1; i <= 10; i++) {
    if (i === 5) {
        break;  // Exit loop when i equals 5
    }
    console.log(i);
}
// Output: 1 2 3 4

b) continue Statement

Skips the current iteration and continues with the next iteration.

Example:

for (let i = 1; i <= 5; i++) {
    if (i === 3) {
        continue;  // Skip when i equals 3
    }
    console.log(i);
}
// Output: 1 2 4 5 (3 is skipped)

c) return Statement

Exits a function and optionally returns a value.

Example:

function checkEven(num) {
    if (num % 2 === 0) {
        return true;
    }
    return false;
}
console.log(checkEven(4));  // Output: true
console.log(checkEven(7));  // Output: false

Summary Table

Control Statement Type Purpose Use Case
if Conditional Single condition check Validate user input
if...else Conditional Two-way decision Display pass/fail
if...else if...else Conditional Multiple conditions Grade calculation
switch Conditional Multiple discrete values Menu selection
for Loop Fixed iterations Array processing
while Loop Condition-based repetition Input validation
do...while Loop Execute at least once Menu display
for...in Loop Object property iteration Display object data
for...of Loop Array/string iteration Process array elements
break Jump Exit loop/switch Early termination
continue Jump Skip iteration Filter processing
return Jump Exit function Return result

Key Differences:

  • Conditional vs Loop: Conditional statements make decisions; loops repeat code
  • while vs do...while: while checks condition first; do...while executes once before checking
  • for...in vs for...of: for...in iterates over keys/properties; for...of iterates over values
  • break vs continue: break exits completely; continue skips to next iteration

Mark Distribution (Part b):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 13(b) - MARK DISTRIBUTION (Total: 8 marks)        │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Conditional Statements                      │ 3 marks    │
│    - if statement with syntax and example      │            │
│    - if...else statement with example          │            │
│    - if...else if...else with example          │            │
│    - switch statement with syntax and example  │            │
│                                                │            │
│ 2. Loop Statements                             │ 3 marks    │
│    - for loop with syntax and example          │            │
│    - while loop with example                   │            │
│    - do...while loop with example              │            │
│    - for...in loop with example                │            │
│    - for...of loop with example                │            │
│                                                │            │
│ 3. Jump Statements                             │ 2 marks    │
│    - break statement with example              │            │
│    - continue statement with example           │            │
│    - return statement with example             │            │
│    - Summary table and key differences         │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Three Components (Section 3.2, adapted)
Total: 6 marks (Part a) + 8 marks (Part b) = 14 marks

Question 14 (14 marks)

a) How are event handlers registered in JavaScript? Write the code for an HTML document with embedded JavaScript scripts, which initially displays a paragraph with text "Welcome" and a button titled "Click". When the button is clicked, the message "Hello from JavaScript" in bold should replace the paragraph text. (8 marks)

Answer:

Event Handler Registration in JavaScript

Event handlers are functions that execute in response to specific events (clicks, mouse movements, key presses, etc.). JavaScript provides three main methods to register event handlers:


Methods of Event Handler Registration

1. Inline Event Handlers (HTML Attribute)

Event handlers defined directly in HTML elements using event attributes.

Syntax:

<button onclick="functionName()">Click Me</button>

Advantages: Simple, direct
Disadvantages: Mixes HTML and JavaScript, harder to maintain, can only attach one handler


2. Traditional DOM Event Handlers (Property Assignment)

Assign event handler as a property of the DOM element.

Syntax:

element.onclick = function() {
    // code
};

Advantages: Separates HTML and JavaScript
Disadvantages: Can only attach one handler per event


3. Modern Event Listeners (addEventListener)

The recommended modern approach for registering event handlers.

Syntax:

element.addEventListener('event', functionName);

Advantages:

  • Multiple handlers can be attached to same event
  • Better control with event propagation
  • Can remove listeners with removeEventListener()
  • Does not overwrite existing handlers

Complete Implementation

Here's the complete solution demonstrating all three methods, with the main implementation using the modern approach:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Event Handler Example</title>
</head>
<body>
    <h1>Event Handler Demo</h1>

    <!-- Main Implementation: Initially displays "Welcome" -->
    <p id="message">Welcome</p>
    <button id="clickButton">Click</button>

    <hr>

    <!-- Additional demonstrations of event handler registration methods -->
    <h3>Event Registration Methods:</h3>

    <!-- Method 1: Inline Event Handler -->
    <button onclick="inlineHandler()">
        Method 1: Inline Handler
    </button>
    <p id="inline-result"></p>

    <!-- Method 2: Traditional DOM Property -->
    <button id="propertyButton">
        Method 2: Property Assignment
    </button>
    <p id="property-result"></p>

    <!-- Method 3: Modern addEventListener -->
    <button id="listenerButton">
        Method 3: Event Listener
    </button>
    <p id="listener-result"></p>

    <script>
        // ===== MAIN IMPLEMENTATION =====
        // Using modern addEventListener method (recommended)

        // Get references to DOM elements
        const messageElement = document.getElementById('message');
        const clickButton = document.getElementById('clickButton');

        // Register click event handler using addEventListener
        clickButton.addEventListener('click', function() {
            // Replace paragraph text with bold "Hello from JavaScript"
            messageElement.innerHTML = '<strong>Hello from JavaScript</strong>';
        });

        // Alternative: Using arrow function (modern ES6 syntax)
        // clickButton.addEventListener('click', () => {
        //     messageElement.innerHTML = '<strong>Hello from JavaScript</strong>';
        // });


        // ===== DEMONSTRATION OF ALL THREE METHODS =====

        // Method 1: Inline Event Handler (defined in HTML onclick attribute)
        function inlineHandler() {
            document.getElementById('inline-result').innerHTML =
                '<strong>Inline handler executed!</strong>';
        }

        // Method 2: Traditional DOM Property Assignment
        const propertyButton = document.getElementById('propertyButton');
        propertyButton.onclick = function() {
            document.getElementById('property-result').innerHTML =
                '<strong>Property handler executed!</strong>';
        };

        // Method 3: Modern addEventListener (can attach multiple handlers)
        const listenerButton = document.getElementById('listenerButton');

        // First listener
        listenerButton.addEventListener('click', function() {
            document.getElementById('listener-result').innerHTML =
                '<strong>First listener executed!</strong>';
        });

        // Second listener (both will execute - advantage of addEventListener)
        listenerButton.addEventListener('click', function() {
            setTimeout(() => {
                document.getElementById('listener-result').innerHTML +=
                    '<br><em>Second listener also executed!</em>';
            }, 500);
        });


        // ===== ADDITIONAL EVENT HANDLING EXAMPLES =====

        // Example: Named function as event handler
        function handleClick() {
            console.log('Named function handler');
        }
        // Can be used as: element.addEventListener('click', handleClick);

        // Example: Event object parameter
        clickButton.addEventListener('mouseenter', function(event) {
            console.log('Mouse entered button');
            console.log('Event type:', event.type);
            console.log('Target element:', event.target);
        });

        // Example: Removing event listener
        function temporaryHandler() {
            console.log('This handler will be removed');
        }
        clickButton.addEventListener('dblclick', temporaryHandler);
        // To remove: clickButton.removeEventListener('dblclick', temporaryHandler);
    </script>
</body>
</html>

Explanation

1. HTML Structure:

  • Paragraph with id="message" initially contains "Welcome"
  • Button with id="clickButton" titled "Click"
  • Additional demonstration buttons showing all three event registration methods

2. JavaScript Event Handling:

Main Implementation (Modern Approach):

clickButton.addEventListener('click', function() {
    messageElement.innerHTML = '<strong>Hello from JavaScript</strong>';
});
  • Gets reference to button and paragraph using getElementById()
  • Registers click event using addEventListener()
  • When clicked, replaces paragraph innerHTML with bold text using <strong> tag

3. Three Event Registration Methods Demonstrated:

Method Code Example Pros Cons
Inline onclick="functionName()" Simple, direct Mixes HTML/JS, one handler only
Property element.onclick = function() Separates HTML/JS One handler only, can be overwritten
addEventListener element.addEventListener('click', fn) Multiple handlers, modern, flexible Slightly more verbose

4. Key Concepts:

  • DOM Access: document.getElementById() retrieves element reference
  • Event Registration: addEventListener() is the modern standard
  • innerHTML: Modifies content including HTML tags (<strong> for bold)
  • Event Types: 'click', 'mouseenter', 'dblclick', 'keypress', etc.

5. Execution Flow:

  1. Page loads → Paragraph displays "Welcome"
  2. User clicks button → Event fires
  3. Event handler executes → Changes innerHTML
  4. Paragraph now displays "Hello from JavaScript" in bold

Simpler Version (Minimal Code):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Simple Event Handler</title>
</head>
<body>
    <p id="message">Welcome</p>
    <button id="clickButton">Click</button>

    <script>
        document.getElementById('clickButton').addEventListener('click', function() {
            document.getElementById('message').innerHTML = '<strong>Hello from JavaScript</strong>';
        });
    </script>
</body>
</html>

This minimal version fulfills all requirements while demonstrating clean, modern JavaScript event handling.

Mark Distribution (Part a):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 14(a) - MARK DISTRIBUTION (Total: 8 marks)        │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Event Handler Registration Explanation     │ 3 marks    │
│    - Three methods of registration             │            │
│    - Inline HTML attribute method              │            │
│    - DOM property assignment method            │            │
│    - addEventListener method (modern)          │            │
│    - Advantages and disadvantages of each      │            │
│                                                │            │
│ 2. Complete HTML/JavaScript Implementation    │ 5 marks    │
│    - HTML structure (paragraph, button)        │            │
│    - DOM element selection (getElementById)    │            │
│    - Event listener registration (click event) │            │
│    - Event handler function implementation     │            │
│    - innerHTML manipulation for bold text      │            │
│    - Proper functionality demonstration        │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Theory + Implementation (Section 3.2, Pattern 5)

b) What are class selectors in CSS? Suppose that it is required to display the text content of p tags in two different styles depending on the context. (6 marks)

Style 1 - text should be displayed in blue colour, right aligned, underlined, with font style of italics and spacing between the words of text set to 2 cm.

Style 2 - text should be displayed with a background colour of yellow, blue colour border, and with a padding of 1.5 cm.

Write the equivalent CSS style rules.

Answer:

CSS Class Selectors

Definition: A class selector in CSS is used to select and style multiple HTML elements that share the same class attribute. Class selectors begin with a dot (.) followed by the class name.

Key Characteristics:

  • Reusability: Can be applied to multiple elements across the page
  • Syntax: .className { property: value; }
  • HTML Usage: <element class="className">
  • Multiple Classes: Elements can have multiple classes: class="class1 class2"
  • Case-Sensitive: Class names are case-sensitive
  • Naming: Can include letters, numbers, hyphens, and underscores (must start with letter)

Advantages:

  • Flexibility: Same class can be applied to different element types
  • Maintainability: Change style once, affects all elements with that class
  • Specificity: More specific than element selectors, less than ID selectors

Complete Implementation

HTML Document with CSS Class Selectors:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Class Selectors Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
            background-color: #f5f5f5;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        /* Style 1: Blue, right-aligned, underlined, italics, word spacing 2cm */
        .style1 {
            color: blue;
            text-align: right;
            text-decoration: underline;
            font-style: italic;
            word-spacing: 2cm;
        }

        /* Style 2: Yellow background, blue border, padding 1.5cm */
        .style2 {
            background-color: yellow;
            border: 2px solid blue;
            padding: 1.5cm;
        }

        h2 {
            color: #333;
            border-bottom: 2px solid #4CAF50;
            padding-bottom: 10px;
            margin-top: 30px;
        }

        .label {
            font-weight: bold;
            color: #666;
            margin-top: 20px;
            display: block;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>CSS Class Selectors Demonstration</h1>

        <h2>Style 1 Examples</h2>
        <span class="label">Paragraph with Style 1:</span>
        <p class="style1">
            This paragraph demonstrates Style 1 with blue color, right alignment,
            underline, italics, and 2cm word spacing.
        </p>

        <span class="label">Another Paragraph with Style 1:</span>
        <p class="style1">
            The quick brown fox jumps over the lazy dog.
        </p>

        <h2>Style 2 Examples</h2>
        <span class="label">Paragraph with Style 2:</span>
        <p class="style2">
            This paragraph demonstrates Style 2 with yellow background,
            blue border, and 1.5cm padding around the content.
        </p>

        <span class="label">Another Paragraph with Style 2:</span>
        <p class="style2">
            CSS class selectors allow us to apply the same styling
            to multiple elements efficiently and maintain consistency.
        </p>

        <h2>Combining Multiple Classes</h2>
        <span class="label">Paragraph with Both Style 1 and Style 2:</span>
        <p class="style1 style2">
            This paragraph has both classes applied, demonstrating how
            multiple classes can be combined on a single element.
        </p>
    </div>
</body>
</html>

CSS Style Rules (Standalone)

Style 1: Blue, Right-Aligned, Underlined, Italics, 2cm Word Spacing

.style1 {
    color: blue;                    /* Text color: blue */
    text-align: right;              /* Horizontal alignment: right */
    text-decoration: underline;     /* Underline the text */
    font-style: italic;             /* Italic font style */
    word-spacing: 2cm;              /* Space between words: 2cm */
}

Style 2: Yellow Background, Blue Border, 1.5cm Padding

.style2 {
    background-color: yellow;       /* Background: yellow */
    border: 2px solid blue;         /* Border: 2px solid blue */
    padding: 1.5cm;                 /* Padding: 1.5cm on all sides */
}

HTML Usage Examples

<!-- Paragraph with Style 1 -->
<p class="style1">
    This text will be blue, right-aligned, underlined, italic, with 2cm word spacing.
</p>

<!-- Paragraph with Style 2 -->
<p class="style2">
    This text will have yellow background, blue border, and 1.5cm padding.
</p>

<!-- Paragraph with both styles (multiple classes) -->
<p class="style1 style2">
    This text combines both styling approaches.
</p>

<!-- Different element types can use same class -->
<div class="style1">This is a div with Style 1</div>
<span class="style2">This is a span with Style 2</span>

Detailed Property Explanations

Style 1 Properties:

Property Value Description
color blue Sets text color to blue
text-align right Aligns text to the right edge
text-decoration underline Adds underline to text
font-style italic Makes text italic/slanted
word-spacing 2cm Sets 2cm space between words

Style 2 Properties:

Property Value Description
background-color yellow Sets yellow background
border 2px solid blue 2px thick solid blue border
padding 1.5cm 1.5cm padding on all sides

Class Selector vs ID Selector vs Element Selector

Comparison Table:

Selector Type Syntax HTML Usage Specificity Reusability
Class .className class="className" Medium Multiple elements
ID #idName id="idName" High Single element (unique)
Element elementName (element itself) Low All elements of that type

Example:

/* Element Selector - applies to ALL p elements */
p {
    font-size: 16px;
}

/* Class Selector - applies to elements with class="highlight" */
.highlight {
    background-color: yellow;
}

/* ID Selector - applies to single element with id="unique" */
#unique {
    color: red;
}

Benefits of Using Class Selectors

  1. Reusability: Apply same style to multiple elements
  2. Maintainability: Change once, update everywhere
  3. Flexibility: Different elements can share same styling
  4. Organization: Group related styles logically
  5. Specificity Control: More targeted than element selectors
  6. Multiple Classes: Combine styles on single element

Best Practices:

  • Use descriptive class names (.warning, .success, not .red, .green)
  • Follow naming conventions (BEM, OOCSS, etc.)
  • Avoid styling based on appearance names
  • Keep class names lowercase with hyphens (.main-content)
  • Don't overuse - sometimes element or ID selectors are more appropriate

Mark Distribution (Part b):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 14(b) - MARK DISTRIBUTION (Total: 6 marks)        │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. CSS Class Selectors Explanation            │ 2 marks    │
│    - Definition of class selectors             │            │
│    - Syntax and characteristics                │            │
│    - Reusability and advantages                │            │
│    - Difference from ID and element selectors  │            │
│                                                │            │
│ 2. Style 1 CSS Implementation                  │ 2 marks    │
│    - Blue color                                │            │
│    - Right alignment                           │            │
│    - Underline decoration                      │            │
│    - Italic font style                         │            │
│    - 2cm word spacing                          │            │
│                                                │            │
│ 3. Style 2 CSS Implementation                  │ 2 marks    │
│    - Yellow background color                   │            │
│    - Blue border (2px solid)                   │            │
│    - 1.5cm padding                             │            │
│    - Complete working HTML demonstration       │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Three Components (Section 2.2, Pattern 2)
Total: 8 marks (Part a) + 6 marks (Part b) = 14 marks

Module III — Module III
Question 15 (14 marks)

a) Explain any six string handling functions used in PHP with example. (6 marks)

Answer:

PHP provides numerous built-in functions for string manipulation. Here are six commonly used string handling functions with detailed examples:


1. strlen() - String Length

Purpose: Returns the length of a string (number of characters).

Syntax: strlen(string $string): int

Example:

<?php
$text = "Web Programming";
$length = strlen($text);
echo "The string '$text' has $length characters";
// Output: The string 'Web Programming' has 15 characters

$password = "secure123";
if (strlen($password) >= 8) {
    echo "Password is strong enough";
} else {
    echo "Password too short";
}
// Output: Password is strong enough
?>

2. str_replace() - String Replace

Purpose: Replaces all occurrences of a search string with a replacement string.

Syntax: str_replace(mixed $search, mixed $replace, mixed $subject): string|array

Example:

<?php
$text = "I love Java programming";
$new_text = str_replace("Java", "PHP", $text);
echo $new_text;
// Output: I love PHP programming

// Replace multiple values
$string = "The quick brown fox";
$result = str_replace(["quick", "fox"], ["slow", "turtle"], $string);
echo $result;
// Output: The slow brown turtle

// Case-sensitive replacement
$email = "user@EXAMPLE.com";
$clean_email = str_replace("EXAMPLE", "example", $email);
echo $clean_email;
// Output: user@example.com
?>

3. substr() - Extract Substring

Purpose: Returns a portion of a string.

Syntax: substr(string $string, int $offset, ?int $length = null): string

Example:

<?php
$text = "Hello World";

// Extract from position 6 to end
echo substr($text, 6);  // Output: World

// Extract 5 characters starting from position 0
echo substr($text, 0, 5);  // Output: Hello

// Extract using negative offset (from end)
echo substr($text, -5);  // Output: World

// Extract middle portion
$filename = "document.pdf";
$extension = substr($filename, -3);
echo "File extension: $extension";
// Output: File extension: pdf
?>

4. strtolower() and strtoupper() - Case Conversion

Purpose: Converts a string to lowercase or uppercase.

Syntax:

  • strtolower(string $string): string
  • strtoupper(string $string): string

Example:

<?php
$text = "Web Programming CST463";

// Convert to lowercase
$lowercase = strtolower($text);
echo $lowercase;
// Output: web programming cst463

// Convert to uppercase
$uppercase = strtoupper($text);
echo $uppercase;
// Output: WEB PROGRAMMING CST463

// Case-insensitive comparison
$input = "HELLO";
if (strtolower($input) == "hello") {
    echo "Match found!";
}
// Output: Match found!

// First letter uppercase
$name = "john doe";
$proper_name = ucwords($name);
echo $proper_name;
// Output: John Doe
?>

5. strpos() - Find Position of Substring

Purpose: Finds the position of the first occurrence of a substring in a string.

Syntax: strpos(string $haystack, string $needle, int $offset = 0): int|false

Example:

<?php
$text = "Learning PHP is fun and PHP is powerful";

// Find first occurrence of "PHP"
$position = strpos($text, "PHP");
echo "First occurrence of PHP at position: $position";
// Output: First occurrence of PHP at position: 9

// Check if substring exists
$email = "user@example.com";
if (strpos($email, "@") !== false) {
    echo "Valid email format";
} else {
    echo "Invalid email";
}
// Output: Valid email format

// Case-sensitive search
$string = "Hello World";
$pos = strpos($string, "world");  // Won't find (lowercase)
if ($pos === false) {
    echo "Not found (case-sensitive)";
}
// Output: Not found (case-sensitive)

// Use stripos() for case-insensitive
$pos2 = stripos($string, "world");  // Will find
echo "\nFound at position: $pos2";
// Output: Found at position: 6
?>

6. explode() and implode() - String to Array and Vice Versa

Purpose:

  • explode(): Splits a string into an array
  • implode(): Joins array elements into a string

Syntax:

  • explode(string $separator, string $string, int $limit = PHP_INT_MAX): array
  • implode(string $separator, array $array): string

Example:

<?php
// explode() - String to Array
$csv_data = "John,25,john@example.com,Engineer";
$user_data = explode(",", $csv_data);
print_r($user_data);
/* Output:
Array (
    [0] => John
    [1] => 25
    [2] => john@example.com
    [3] => Engineer
)
*/

// Access individual elements
echo "Name: " . $user_data[0];  // Output: Name: John
echo "\nAge: " . $user_data[1]; // Output: Age: 25

// implode() - Array to String
$fruits = array("Apple", "Banana", "Orange", "Mango");
$fruit_string = implode(", ", $fruits);
echo $fruit_string;
// Output: Apple, Banana, Orange, Mango

// Practical use case: Process URL parameters
$url_path = "category/products/electronics";
$segments = explode("/", $url_path);
echo "Category: " . $segments[0];      // Output: Category: category
echo "\nSection: " . $segments[1];     // Output: Section: products
echo "\nSubcategory: " . $segments[2]; // Output: Subcategory: electronics

// Join with different separator
$words = array("PHP", "MySQL", "Web", "Development");
$hashtags = "#" . implode(" #", $words);
echo $hashtags;
// Output: #PHP #MySQL #Web #Development
?>

Summary Table

Function Purpose Input Output Use Case
strlen() Get string length String Integer Validate input length
str_replace() Replace substring String String Find and replace text
substr() Extract portion String + positions String Get file extension
strtolower()/strtoupper() Change case String String Case-insensitive comparison
strpos() Find substring position String Integer/false Check if substring exists
explode()/implode() Array-String conversion String/Array Array/String Process CSV, join words

Additional Useful String Functions:

  • trim() - Remove whitespace from both ends
  • str_word_count() - Count words in string
  • strcmp() - Compare two strings
  • str_repeat() - Repeat a string
  • ucfirst() - Uppercase first character
  • str_pad() - Pad string to certain length

Mark Distribution (Part a):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 15(a) - MARK DISTRIBUTION (Total: 6 marks)        │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Six String Handling Functions Explained    │ 6 marks    │
│    - strlen() with syntax and example (1 mark) │            │
│    - str_replace() with syntax and example     │            │
│      (1 mark)                                  │            │
│    - substr() with syntax and example (1 mark) │            │
│    - strtolower/strtoupper with syntax and     │            │
│      example (1 mark)                          │            │
│    - strpos() with syntax and example (1 mark) │            │
│    - explode/implode with syntax and example   │            │
│      (1 mark)                                  │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Six Equal Components (Section 2.2, Pattern 4 adapted)

b) What is the purpose of the implicit arrays $_POST and $_GET in PHP? Consider that a web page displays a form containing two text boxes (named num1 and num2), where the user enters numeric data. Write a PHP script which collects this form data, finds the sum, difference and the product of the two numbers and then displays the same with suitable messages. Assume that the script is to be embedded in the web page specified by the action attribute of the form and that the method used when the form is submitted is GET. (8 marks)

Answer:

Purpose of $_POST and $_GET Arrays

$_POST and $_GET are PHP superglobal arrays used to collect form data sent to the server.


$_GET Array

Purpose: Collects data sent via URL parameters (query string).

Characteristics:

  • Data is visible in the URL: page.php?name=John&age=25
  • Limited data size (usually ~2000 characters)
  • Can be bookmarked and cached
  • Less secure (data visible in browser history, logs)
  • Suitable for non-sensitive data (search queries, filters, pagination)

Syntax: $_GET['parameter_name']

Example URL: calculator.php?num1=10&num2=5


$_POST Array

Purpose: Collects data sent via HTTP POST method.

Characteristics:

  • Data is NOT visible in URL
  • No size limit (configured in php.ini)
  • Cannot be bookmarked
  • More secure than GET
  • Suitable for sensitive data (passwords, forms with large data)

Syntax: $_POST['parameter_name']


Comparison Table

Aspect $_GET $_POST
Visibility Visible in URL Hidden in request body
Security Less secure More secure
Data Size Limited (~2000 chars) Large (unlimited)
Bookmarkable Yes No
Caching Can be cached Not cached
Use Cases Search, filters, pagination Login, registration, file upload

Complete Implementation

HTML Form + PHP Script (Using GET Method)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Number Calculator</title>
</head>
<body>
    <h2>Number Calculator</h2>

    <!-- HTML Form using GET method -->
    <form method="GET" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
        <label for="num1">Enter First Number:</label><br>
        <input type="number"
               id="num1"
               name="num1"
               step="any"
               required
               value="<?php echo isset($_GET['num1']) ? htmlspecialchars($_GET['num1']) : ''; ?>"><br><br>

        <label for="num2">Enter Second Number:</label><br>
        <input type="number"
               id="num2"
               name="num2"
               step="any"
               required
               value="<?php echo isset($_GET['num2']) ? htmlspecialchars($_GET['num2']) : ''; ?>"><br><br>

        <button type="submit">Calculate</button>
    </form>

    <?php
    // PHP Script to process form data using GET method
    if (isset($_GET['num1']) && isset($_GET['num2'])) {
        // Retrieve values from $_GET array
        $num1 = $_GET['num1'];
        $num2 = $_GET['num2'];

        // Validate that inputs are numeric
        if (is_numeric($num1) && is_numeric($num2)) {
            // Convert to float for decimal support
            $num1 = floatval($num1);
            $num2 = floatval($num2);

            // Perform calculations
            $sum = $num1 + $num2;
            $difference = $num1 - $num2;
            $product = $num1 * $num2;

            // Display results
            echo '<h3>Calculation Results:</h3>';

            echo '<p><strong>First Number:</strong> ' . $num1 . '</p>';
            echo '<p><strong>Second Number:</strong> ' . $num2 . '</p>';

            echo '<hr>';

            echo '<p><strong>Sum:</strong> ' . $num1 . ' + ' . $num2 . ' = <strong>' . $sum . '</strong></p>';
            echo '<p><strong>Difference:</strong> ' . $num1 . ' - ' . $num2 . ' = <strong>' . $difference . '</strong></p>';
            echo '<p><strong>Product:</strong> ' . $num1 . ' × ' . $num2 . ' = <strong>' . $product . '</strong></p>';

            // Additional: Division (with zero check)
            if ($num2 != 0) {
                $division = $num1 / $num2;
                echo '<p><strong>Division:</strong> ' . $num1 . ' ÷ ' . $num2 . ' = <strong>' . round($division, 2) . '</strong></p>';
            } else {
                echo '<p><strong>Division:</strong> Cannot divide by zero</p>';
            }
        } else {
            // Error: Non-numeric input
            echo '<h3>Error!</h3>';
            echo '<p>Please enter valid numeric values.</p>';
        }
    }
    ?>
</body>
</html>

Explanation

1. HTML Form Structure:

<form method="GET" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
  • method="GET": Specifies data will be sent via URL parameters
  • action: Points to the same page (self-processing form)
  • $_SERVER['PHP_SELF'] returns the current script filename

2. Form Input Fields:

<input type="number" name="num1" required>
<input type="number" name="num2" required>
  • type="number" provides numeric input validation
  • name attribute defines the key in $_GET array
  • required ensures fields are not empty

3. PHP Processing Logic:

Step 1: Check if Data is Submitted

if (isset($_GET['num1']) && isset($_GET['num2'])) {
  • isset() checks if parameters exist in $_GET array
  • Prevents errors when page first loads

Step 2: Retrieve Values

$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
  • Access data using parameter names as array keys
  • Values are retrieved as strings initially

Step 3: Validate Input

if (is_numeric($num1) && is_numeric($num2)) {
    $num1 = floatval($num1);
    $num2 = floatval($num2);
  • is_numeric() validates numeric input
  • floatval() converts to floating-point number for decimal support

Step 4: Perform Calculations

$sum = $num1 + $num2;
$difference = $num1 - $num2;
$product = $num1 * $num2;
  • Simple arithmetic operations

Step 5: Display Results

echo "Sum: $num1 + $num2 = $sum";
echo "Difference: $num1 - $num2 = $difference";
echo "Product: $num1 × $num2 = $product";

How $_GET Works (Flow Diagram)

1. User fills form:
   num1 = 10
   num2 = 5

2. User clicks Submit

3. Browser sends GET request:
   calculator.php?num1=10&num2=5

4. PHP receives data in $_GET array:
   $_GET = [
       'num1' => '10',
       'num2' => '5'
   ]

5. PHP processes:
   $num1 = 10, $num2 = 5
   $sum = 15
   $difference = 5
   $product = 50

6. Results displayed on same page

Security Considerations

1. Input Validation:

if (is_numeric($num1) && is_numeric($num2)) {
    // Process only if valid
}

2. Output Escaping:

echo htmlspecialchars($_GET['num1']);
  • Prevents XSS (Cross-Site Scripting) attacks

3. Why GET is Acceptable Here:

  • No sensitive data (just numbers for calculation)
  • Results can be bookmarked/shared
  • No database operations

When to Use POST Instead:

  • Sensitive data (passwords, personal information)
  • Large amounts of data
  • Database modifications (INSERT, UPDATE, DELETE)

Test Cases

Test Case 1:

  • Input: num1=10, num2=5
  • Output:
    • Sum: 10 + 5 = 15
    • Difference: 10 - 5 = 5
    • Product: 10 × 5 = 50

Test Case 2:

  • Input: num1=7.5, num2=2.3
  • Output:
    • Sum: 7.5 + 2.3 = 9.8
    • Difference: 7.5 - 2.3 = 5.2
    • Product: 7.5 × 2.3 = 17.25

Test Case 3:

  • Input: num1=-5, num2=3
  • Output:
    • Sum: -5 + 3 = -2
    • Difference: -5 - 3 = -8
    • Product: -5 × 3 = -15

Mark Distribution (Part b):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 15(b) - MARK DISTRIBUTION (Total: 8 marks)        │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. $_GET and $_POST Explanation                │ 2 marks    │
│    - Purpose and characteristics of $_GET      │            │
│    - Purpose and characteristics of $_POST     │            │
│    - Differences and use cases                 │            │
│                                                │            │
│ 2. HTML Form Implementation                    │ 2 marks    │
│    - Form structure with method="GET"          │            │
│    - Two text input fields (num1, num2)        │            │
│    - Submit button                             │            │
│                                                │            │
│ 3. PHP Script for Calculations                 │ 4 marks    │
│    - Retrieving data from $_GET                │            │
│    - Sum calculation and display               │            │
│    - Difference calculation and display        │            │
│    - Product calculation and display           │            │
│    - Error handling and validation             │            │
│    - Complete working implementation           │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Three Components (Section 3.2, adapted)
Total: 6 marks (Part a) + 8 marks (Part b) = 14 marks

Question 16 (14 marks)

a) Illustrate with a sample PHP script, how functions are implemented in PHP. (6 marks)

Answer:

Functions in PHP are reusable blocks of code that perform specific tasks. They help organize code, improve reusability, and make programs more maintainable.


Function Basics in PHP

Function Declaration Syntax:

function functionName($parameter1, $parameter2, ...) {
    // Function body
    // Code to execute
    return $value;  // Optional
}

Function Call:

$result = functionName($arg1, $arg2);

Comprehensive PHP Function Examples

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PHP Functions Demonstration</title>
</head>
<body>
    <h1>PHP Functions - Complete Guide</h1>

    <?php
    // ===== 1. SIMPLE FUNCTION (No Parameters, No Return) =====
    echo '<h2>1. Simple Function (No Parameters)</h2>';

    function greet() {
        echo "Hello, welcome to PHP programming!";
    }

    greet();
    echo '<hr>';


    // ===== 2. FUNCTION WITH PARAMETERS =====
    echo '<h2>2. Function with Parameters</h2>';

    function greetUser($name) {
        echo "Hello, $name! Welcome to CST463.";
    }

    greetUser("Alice");
    echo '<br>';
    greetUser("Bob");
    echo '<hr>';


    // ===== 3. FUNCTION WITH RETURN VALUE =====
    echo '<h2>3. Function with Return Value</h2>';

    function add($a, $b) {
        $sum = $a + $b;
        return $sum;
    }

    $result = add(10, 5);
    echo "Sum of 10 and 5 is: $result<br>";
    echo "Sum of 20 and 30 is: " . add(20, 30);
    echo '<hr>';


    // ===== 4. FUNCTION WITH DEFAULT PARAMETERS =====
    echo '<h2>4. Function with Default Parameters</h2>';

    function calculateArea($length, $width = 5) {
        return $length * $width;
    }

    echo "Area with both parameters (10, 6): " . calculateArea(10, 6) . "<br>";
    echo "Area with default width (10): " . calculateArea(10);
    echo '<hr>';


    // ===== 5. FUNCTION WITH MULTIPLE RETURN VALUES (Array) =====
    echo '<h2>5. Function Returning Multiple Values</h2>';

    function calculate($num1, $num2) {
        $sum = $num1 + $num2;
        $difference = $num1 - $num2;
        $product = $num1 * $num2;
        $quotient = ($num2 != 0) ? $num1 / $num2 : "Undefined";

        return array(
            'sum' => $sum,
            'difference' => $difference,
            'product' => $product,
            'quotient' => $quotient
        );
    }

    $results = calculate(20, 4);
    echo "Results for 20 and 4:<br>";
    echo "Sum: " . $results['sum'] . "<br>";
    echo "Difference: " . $results['difference'] . "<br>";
    echo "Product: " . $results['product'] . "<br>";
    echo "Quotient: " . $results['quotient'];
    echo '<hr>';


    // ===== 6. FUNCTION WITH TYPE DECLARATIONS (PHP 7+) =====
    echo '<h2>6. Function with Type Declarations</h2>';

    function multiply(int $a, int $b): int {
        return $a * $b;
    }

    function divide(float $a, float $b): float {
        return $a / $b;
    }

    echo "Multiply (5, 3): " . multiply(5, 3) . "<br>";
    echo "Divide (10.5, 2.5): " . divide(10.5, 2.5);
    echo '<hr>';


    // ===== 7. FUNCTION WITH VARIABLE SCOPE =====
    echo '<h2>7. Variable Scope in Functions</h2>';

    $globalVar = "I am global";

    function demonstrateScope() {
        global $globalVar;  // Access global variable
        $localVar = "I am local";

        echo "Inside function - Global: $globalVar<br>";
        echo "Inside function - Local: $localVar<br>";
    }

    demonstrateScope();
    echo "Outside function - Global: $globalVar";
    echo '<hr>';


    // ===== 8. RECURSIVE FUNCTION =====
    echo '<h2>8. Recursive Function (Factorial)</h2>';

    function factorial($n) {
        if ($n <= 1) {
            return 1;
        }
        return $n * factorial($n - 1);
    }

    echo "Factorial of 5: " . factorial(5) . "<br>";
    echo "Factorial of 7: " . factorial(7);
    echo '<hr>';


    // ===== 9. FUNCTION WITH VARIABLE NUMBER OF ARGUMENTS =====
    echo '<h2>9. Variable Arguments (func_get_args)</h2>';

    function sum_all() {
        $args = func_get_args();
        $total = 0;
        foreach ($args as $num) {
            $total += $num;
        }
        return $total;
    }

    echo "Sum of (1, 2, 3): " . sum_all(1, 2, 3) . "<br>";
    echo "Sum of (5, 10, 15, 20): " . sum_all(5, 10, 15, 20) . "<br>";
    echo "Sum of (100, 200): " . sum_all(100, 200);
    echo '<hr>';


    // ===== 10. PRACTICAL EXAMPLE: Grade Calculator =====
    echo '<h2>10. Practical Example: Student Grade Calculator</h2>';

    function calculateGrade($marks) {
        if ($marks >= 90) {
            return "A+";
        } elseif ($marks >= 80) {
            return "A";
        } elseif ($marks >= 70) {
            return "B";
        } elseif ($marks >= 60) {
            return "C";
        } elseif ($marks >= 50) {
            return "D";
        } else {
            return "F";
        }
    }

    function getGradeMessage($marks) {
        $grade = calculateGrade($marks);
        $status = ($marks >= 50) ? "Passed" : "Failed";

        return "Marks: $marks | Grade: $grade | Status: $status";
    }

    echo getGradeMessage(95) . "<br>";
    echo getGradeMessage(75) . "<br>";
    echo getGradeMessage(45) . "<br>";
    ?>

</body>
</html>

Explanation of Function Concepts

1. Function Declaration:

function functionName($parameter) {
    // code
    return $value;
}

2. Function Parameters:

  • Required Parameters: Must be provided
  • Optional Parameters: Have default values
  • Variable Arguments: Accept any number of arguments

3. Return Values:

  • Use return statement to send data back
  • Can return any data type (string, int, array, object)
  • Functions without return statement return NULL

4. Variable Scope:

  • Local: Variables declared inside function
  • Global: Variables declared outside function
  • Use global keyword to access global variables

5. Function Types:

Type Description Example
Simple No parameters, no return function greet()
Parameters Accepts input function add($a, $b)
Return Value Returns output return $sum;
Default Params Optional parameters function test($a = 5)
Recursive Calls itself function factorial($n)

Key Features of PHP Functions

  1. Code Reusability: Write once, use many times
  2. Modularity: Break complex problems into smaller pieces
  3. Maintainability: Easier to update and debug
  4. Type Safety: (PHP 7+) Declare parameter and return types
  5. Variable Arguments: Flexible parameter count
  6. Anonymous Functions: Lambda functions and closures

Mark Distribution (Part a):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 16(a) - MARK DISTRIBUTION (Total: 6 marks)        │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. PHP Function Implementation Demonstration   │ 6 marks    │
│    - Function declaration syntax               │            │
│    - Basic function with parameters            │            │
│    - Function with return value                │            │
│    - Default parameter values example          │            │
│    - Pass by reference example                 │            │
│    - Variable arguments example                │            │
│    - Recursive function example (optional)     │            │
│    - Comprehensive working examples            │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Complete Implementation (Section 2.2, Pattern 5)

b) Why is PHP considered to be dynamically typed? Distinguish between implode and explode function in PHP with suitable examples. (8 marks)

Answer:

Why PHP is Dynamically Typed

Dynamic Typing means that variable types are determined at runtime rather than compile time, and variables can change types during execution.


Dynamic Typing in PHP

Definition: In PHP, you don't need to declare a variable's type explicitly. The type is automatically determined based on the value assigned to it, and it can change during script execution.

Key Characteristics:

  1. No Type Declaration Required:

    $variable = 10;  // No need to specify "int"
  2. Type Changes at Runtime:

    $data = "Hello";   // String
    $data = 100;       // Now integer
    $data = 3.14;      // Now float
    $data = array();   // Now array
  3. Automatic Type Conversion (Type Juggling):

    $number = "10";    // String
    $result = $number + 5;  // PHP converts "10" to integer 10
    echo $result;      // Output: 15

Demonstration of Dynamic Typing

<?php
// Dynamic Typing Examples

echo "<h3>Dynamic Typing Demonstration</h3>";

// Example 1: Variable changes type
$variable = "Hello World";
echo "Type: " . gettype($variable) . " | Value: $variable<br>";
// Output: Type: string | Value: Hello World

$variable = 42;
echo "Type: " . gettype($variable) . " | Value: $variable<br>";
// Output: Type: integer | Value: 42

$variable = 3.14159;
echo "Type: " . gettype($variable) . " | Value: $variable<br>";
// Output: Type: double | Value: 3.14159

$variable = true;
echo "Type: " . gettype($variable) . " | Value: " . ($variable ? 'true' : 'false') . "<br>";
// Output: Type: boolean | Value: true

$variable = array(1, 2, 3);
echo "Type: " . gettype($variable) . "<br>";
// Output: Type: array

// Example 2: Automatic Type Conversion
$string_number = "25";
$integer = 10;
$sum = $string_number + $integer;
echo "<br>\"25\" + 10 = $sum (Type: " . gettype($sum) . ")<br>";
// Output: "25" + 10 = 35 (Type: integer)

// Example 3: Type Juggling in Operations
$result = "5" * "10";  // Both strings, but PHP converts to integers
echo "\"5\" * \"10\" = $result (Type: " . gettype($result) . ")<br>";
// Output: "5" * "10" = 50 (Type: integer)

// Example 4: Mixed Operations
$mixed = "10 apples" + 5;
echo "\"10 apples\" + 5 = $mixed<br>";
// Output: "10 apples" + 5 = 15 (PHP extracts 10 from string)
?>

Dynamic vs Static Typing Comparison

Aspect Dynamic Typing (PHP, Python) Static Typing (Java, C++)
Type Declaration Not required Required at compile time
Type Checking Runtime Compile time
Type Changes Allowed Not allowed
Flexibility High Low
Error Detection Runtime errors Compile-time errors
Example $x = 5; int x = 5;

Advantages of Dynamic Typing

  1. Faster Development: No need to declare types
  2. Flexibility: Variables can hold any type
  3. Less Verbose: Less code to write
  4. Rapid Prototyping: Quick to test ideas

Disadvantages

  1. Runtime Errors: Type errors caught only during execution
  2. Less IDE Support: Harder for IDEs to provide type-specific hints
  3. Potential Bugs: Type-related bugs can slip through

Note: PHP 7+ Type Declarations

While PHP is dynamically typed, PHP 7+ introduced optional type declarations for stricter code:

function add(int $a, int $b): int {
    return $a + $b;
}

Distinguish Between implode() and explode()

Both functions work with arrays and strings but in opposite directions.


explode() Function

Purpose: Splits a string into an array based on a delimiter.

Direction: String → Array

Syntax: explode(string $separator, string $string, int $limit = PHP_INT_MAX): array

Parameters:

  • $separator: The delimiter to split by
  • $string: The string to split
  • $limit: (Optional) Maximum number of array elements

implode() Function

Purpose: Joins array elements into a single string with a separator.

Direction: Array → String

Syntax: implode(string $separator, array $array): string

Aliases: join() is an alias of implode()

Parameters:

  • $separator: The glue between array elements
  • $array: The array to join

Comprehensive Examples

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>implode() vs explode() in PHP</title>
</head>
<body>
    <h1>implode() vs explode() Demonstration</h1>

    <?php
    // ===== EXPLODE EXAMPLES =====
    echo "<h2>1. explode() Examples (String → Array)</h2>";

    // Example 1.1: Basic explode
    echo "<h3>Example 1.1: Split CSV Data</h3>";
    $csv_string = "Apple,Banana,Orange,Mango";
    $fruits_array = explode(",", $csv_string);

    echo "<strong>Input String:</strong> $csv_string<br>";
    echo "<strong>Delimiter:</strong> ,<br>";
    echo "<strong>Output Array:</strong><br>";
    echo "<pre>";
    print_r($fruits_array);
    echo "</pre>";
    echo "<hr>";

    // Example 1.2: Split sentence into words
    echo "<h3>Example 1.2: Split Sentence</h3>";
    $sentence = "PHP is a server-side scripting language";
    $words = explode(" ", $sentence);

    echo "<strong>Input:</strong> $sentence<br>";
    echo "<strong>Delimiter:</strong> [space]<br>";
    echo "<strong>Words:</strong><br>";
    foreach ($words as $index => $word) {
        echo "[$index] => $word<br>";
    }
    echo "<hr>";

    // Example 1.3: Split with limit
    echo "<h3>Example 1.3: Explode with Limit</h3>";
    $email = "user@example.com";
    $parts = explode("@", $email, 2);

    echo "<strong>Input:</strong> $email<br>";
    echo "<strong>Delimiter:</strong> @<br>";
    echo "<strong>Limit:</strong> 2<br>";
    echo "Username: " . $parts[0] . "<br>";
    echo "Domain: " . $parts[1];
    echo "<hr>";

    // Example 1.4: Process URL path
    echo "<h3>Example 1.4: Parse URL Path</h3>";
    $url_path = "category/products/electronics/laptops";
    $segments = explode("/", $url_path);

    echo "<strong>URL Path:</strong> $url_path<br>";
    echo "Level 1: " . $segments[0] . " (category)<br>";
    echo "Level 2: " . $segments[1] . " (products)<br>";
    echo "Level 3: " . $segments[2] . " (electronics)<br>";
    echo "Level 4: " . $segments[3] . " (laptops)";
    echo "<hr>";


    // ===== IMPLODE EXAMPLES =====
    echo "<h2>2. implode() Examples (Array → String)</h2>";

    // Example 2.1: Basic implode
    echo "<h3>Example 2.1: Join Array Elements</h3>";
    $colors = array("Red", "Green", "Blue", "Yellow");
    $color_string = implode(", ", $colors);

    echo "<strong>Input Array:</strong><br>";
    echo "<pre>";
    print_r($colors);
    echo "</pre>";
    echo "<strong>Separator:</strong> , <br>";
    echo "<strong>Output String:</strong> $color_string";
    echo "<hr>";

    // Example 2.2: Create HTML list
    echo "<h3>Example 2.2: Generate HTML</h3>";
    $menu_items = array("Home", "About", "Services", "Contact");
    $html_list = "<li>" . implode("</li><li>", $menu_items) . "</li>";

    echo "<strong>Menu Items:</strong><br>";
    echo "<pre>";
    print_r($menu_items);
    echo "</pre>";
    echo "<strong>HTML Output:</strong><br>";
    echo htmlspecialchars("<ul>$html_list</ul>");
    echo "<br><br><strong>Rendered:</strong><br>";
    echo "<ul>$html_list</ul>";
    echo "<hr>";

    // Example 2.3: Create SQL IN clause
    echo "<h3>Example 2.3: SQL Query Generation</h3>";
    $ids = array(101, 102, 103, 104, 105);
    $id_list = implode(",", $ids);
    $sql = "SELECT * FROM users WHERE id IN ($id_list)";

    echo "<strong>IDs Array:</strong> " . print_r($ids, true) . "<br>";
    echo "<strong>Generated SQL:</strong><br>";
    echo "$sql";
    echo "<hr>";

    // Example 2.4: Create hashtags
    echo "<h3>Example 2.4: Social Media Hashtags</h3>";
    $keywords = array("PHP", "WebDevelopment", "Programming", "CST463");
    $hashtags = "#" . implode(" #", $keywords);

    echo "<strong>Keywords:</strong><br>";
    echo "<pre>";
    print_r($keywords);
    echo "</pre>";
    echo "<strong>Hashtags:</strong> $hashtags";
    echo "<hr>";


    // ===== PRACTICAL COMBINATION =====
    echo "<h2>3. Combining explode() and implode()</h2>";

    echo "<h3>Example 3.1: Clean and Format Data</h3>";
    $messy_string = "apple,  banana,orange,   mango  ,grapes";

    // Step 1: Explode into array
    $array = explode(",", $messy_string);

    // Step 2: Trim whitespace from each element
    $cleaned_array = array_map('trim', $array);

    // Step 3: Implode back with consistent formatting
    $clean_string = implode(", ", $cleaned_array);

    echo "<strong>Original:</strong> '$messy_string'<br>";
    echo "<strong>After explode and trim:</strong><br>";
    echo "<pre>";
    print_r($cleaned_array);
    echo "</pre>";
    echo "<strong>After implode:</strong> '$clean_string'";
    echo "<hr>";

    echo "<h3>Example 3.2: Replace Separator</h3>";
    $pipe_separated = "Red|Green|Blue|Yellow";

    // Convert pipe-separated to comma-separated
    $array = explode("|", $pipe_separated);
    $comma_separated = implode(", ", $array);

    echo "<strong>Original (pipe-separated):</strong> $pipe_separated<br>";
    echo "<strong>Converted (comma-separated):</strong> $comma_separated";
    ?>

</body>
</html>

Comparison Table: explode() vs implode()

Aspect explode() implode()
Purpose Split string into array Join array into string
Direction String → Array Array → String
Input String + Delimiter Array + Separator
Output Array String
Common Use Parse CSV, split sentences Create lists, format output
Syntax explode($delimiter, $string) implode($separator, $array)
Example explode(",", "a,b,c")["a","b","c"] implode(",", ["a","b","c"])"a,b,c"
Alias None join()

Practical Use Cases

explode() Use Cases:

  1. Parse CSV Data: Split comma-separated values
  2. Process URLs: Break down URL paths
  3. Split Sentences: Get individual words
  4. Parse Email: Separate username and domain
  5. File Extensions: Extract file name and extension

implode() Use Cases:

  1. Generate SQL: Create IN clauses
  2. Format Output: Display lists with custom separators
  3. Create HTML: Generate list items
  4. Breadcrumbs: Join navigation items
  5. Tags/Keywords: Format for display

Summary

Dynamic Typing in PHP:

  • Variables don't need type declarations
  • Types determined at runtime
  • Variables can change types during execution
  • Provides flexibility but requires careful handling

explode() vs implode():

  • explode(): Breaks strings into arrays (useful for parsing)
  • implode(): Combines arrays into strings (useful for formatting)
  • They are opposite operations, often used together for data transformation

Mark Distribution (Part b):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 16(b) - MARK DISTRIBUTION (Total: 8 marks)        │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. PHP Dynamic Typing Explanation              │ 4 marks    │
│    - Definition of dynamic typing              │            │
│    - How PHP implements dynamic typing         │            │
│    - Examples of type changes at runtime       │            │
│    - Advantages and disadvantages              │            │
│    - Comparison with static typing             │            │
│                                                │            │
│ 2. explode() Function                          │ 2 marks    │
│    - Purpose and syntax                        │            │
│    - Working examples with explanation         │            │
│                                                │            │
│ 3. implode() Function                          │ 2 marks    │
│    - Purpose and syntax                        │            │
│    - Working examples with explanation         │            │
│    - Comparison with explode()                 │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Theory + Two Equal Components (Section 3.2, Pattern 1)
Total: 6 marks (Part a) + 8 marks (Part b) = 14 marks

PART B - Module IV

Question 17 (14 marks) — ---

Question 17(a) - 6 marks

What is the significance of cookies in web? How can a cookie be created and destroyed in PHP?

Answer:

Significance of Cookies in Web

Cookies are small text files stored on the client's browser by web servers to maintain stateful information across multiple HTTP requests. Since HTTP is a stateless protocol, cookies help maintain continuity and user preferences.

Key Significance:

  1. Session Management: Track user login sessions and authentication
  2. Personalization: Store user preferences (theme, language, settings)
  3. Tracking: Monitor user behavior and analytics
  4. Shopping Carts: Remember items in e-commerce applications
  5. User Experience: Remember user choices across visits

Cookie Properties:

  • Stored on client-side (browser)
  • Sent with every HTTP request to the same domain
  • Have expiration dates
  • Limited size (typically 4KB per cookie)
  • Domain and path specific

Creating Cookies in PHP

Syntax:

setcookie(name, value, expire, path, domain, secure, httponly);

Example 1: Basic Cookie Creation

<?php
// Set a cookie that expires in 30 days
$cookie_name = "username";
$cookie_value = "John Doe";
$expiry = time() + (30 * 24 * 60 * 60); // 30 days from now

setcookie($cookie_name, $cookie_value, $expiry, "/");

echo "Cookie '$cookie_name' has been set!";
?>

Example 2: Cookie with Multiple Parameters

<?php
// Set secure cookie with all parameters
setcookie(
    "user_preference",           // Cookie name
    "dark_mode",                 // Cookie value
    time() + 86400,              // Expires in 1 day
    "/",                         // Available across entire domain
    "example.com",               // Domain
    true,                        // Secure (HTTPS only)
    true                         // HTTP only (not accessible via JavaScript)
);
?>

Example 3: Accessing Cookie Values

<?php
// Check if cookie exists and retrieve it
if(isset($_COOKIE['username'])) {
    echo "Welcome back, " . $_COOKIE['username'] . "!";
} else {
    echo "Welcome, Guest!";
}
?>

Destroying Cookies in PHP

To delete a cookie, set its expiration time to a past date.

Method 1: Set Expiry to Past Time

<?php
// Delete cookie by setting expiry to past time
setcookie("username", "", time() - 3600, "/");
echo "Cookie 'username' has been deleted!";
?>

Method 2: Explicit Deletion

<?php
// Delete specific cookie
$cookie_name = "user_preference";
if(isset($_COOKIE[$cookie_name])) {
    // Set cookie with past expiration
    setcookie($cookie_name, "", time() - 3600, "/");
    unset($_COOKIE[$cookie_name]); // Remove from current script
    echo "Cookie deleted successfully!";
} else {
    echo "Cookie does not exist!";
}
?>

Method 3: Delete Multiple Cookies

<?php
// Delete all cookies
foreach($_COOKIE as $cookie_name => $cookie_value) {
    setcookie($cookie_name, "", time() - 3600, "/");
}
echo "All cookies deleted!";
?>

Complete Cookie Management Example

<?php
// cookie_demo.php

// Function to create cookie
function createCookie($name, $value, $days = 30) {
    $expiry = time() + ($days * 24 * 60 * 60);
    setcookie($name, $value, $expiry, "/");
}

// Function to delete cookie
function deleteCookie($name) {
    setcookie($name, "", time() - 3600, "/");
    unset($_COOKIE[$name]);
}

// Create cookies
createCookie("user_id", "12345", 7);
createCookie("user_name", "Alice", 7);
createCookie("theme", "dark", 30);

// Display cookies
echo "<h3>Current Cookies:</h3>";
if(count($_COOKIE) > 0) {
    foreach($_COOKIE as $name => $value) {
        echo "$name: $value<br>";
    }
} else {
    echo "No cookies set.";
}

// Delete specific cookie
if(isset($_GET['delete'])) {
    deleteCookie($_GET['delete']);
    echo "<p>Cookie '" . $_GET['delete'] . "' deleted!</p>";
}
?>

Important Notes:

  1. setcookie() must be called before any output (before HTML or echo statements)
  2. Cookies are automatically sent with every HTTP request to the domain
  3. Cookie changes take effect on the next page load
  4. Users can disable cookies in browser settings
  5. Never store sensitive information (passwords, credit cards) in cookies
  6. Use secure and httponly flags for sensitive cookies

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 17(a) - MARK DISTRIBUTION (Total: 6 marks)        │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Significance of Cookies                     │ 2 marks    │
│    - Definition and purpose                    │            │
│    - Benefits and use cases                    │            │
│                                                │            │
│ 2. Creating Cookies in PHP                     │ 2 marks    │
│    - setcookie() syntax and parameters         │            │
│    - Code examples                             │            │
│                                                │            │
│ 3. Destroying Cookies in PHP                   │ 2 marks    │
│    - Method to delete cookies                  │            │
│    - Code examples                             │            │
│    - Important notes                           │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Three Equal Components (Section 2.2, Pattern 2)

Question 17(b) - 8 marks

Write equivalent PHP statements corresponding to the following:

  • i) Declare an associative array named "marks" to store the key-value pairs ("Ram", 40), ("Alice", 20), ("Raj", 45), ("Mary", 35).
  • ii) Modify the value associated with the key "Ram" to 50.
  • iii) Sort the array and print the sorted key value pairs.
  • iv) The entry identified by the key "Raj"

Answer:

<?php
// ===== SOLUTION TO QUESTION 17(b) =====

echo "<h2>Question 17(b): Associative Array Operations</h2>";

// ===== PART (i): Declare associative array =====
echo "<h3>(i) Declare Associative Array</h3>";

$marks = array(
    "Ram" => 40,
    "Alice" => 20,
    "Raj" => 45,
    "Mary" => 35
);

echo "<strong>Original Array:</strong><br>";
echo "<pre>";
print_r($marks);
echo "</pre>";

// Alternative syntax (PHP 5.4+)
// $marks = ["Ram" => 40, "Alice" => 20, "Raj" => 45, "Mary" => 35];

echo "<hr>";

// ===== PART (ii): Modify value for key "Ram" =====
echo "<h3>(ii) Modify Value for 'Ram'</h3>";

echo "<strong>Before modification:</strong> Ram = " . $marks["Ram"] . "<br>";

$marks["Ram"] = 50;

echo "<strong>After modification:</strong> Ram = " . $marks["Ram"] . "<br>";

echo "<strong>Updated Array:</strong><br>";
echo "<pre>";
print_r($marks);
echo "</pre>";

echo "<hr>";

// ===== PART (iii): Sort the array and print sorted key-value pairs =====
echo "<h3>(iii) Sort Array and Print Sorted Key-Value Pairs</h3>";

// Sort by values in ascending order (maintains key association)
asort($marks);

echo "<strong>Array sorted by values (ascending):</strong><br>";
foreach($marks as $name => $mark) {
    echo "$name: $mark<br>";
}

echo "<br><strong>Sorted Array Structure:</strong><br>";
echo "<pre>";
print_r($marks);
echo "</pre>";

// Additional sorting examples:
echo "<strong>Alternative Sorting Methods:</strong><br><br>";

// Sort by values (descending)
$marks_copy1 = $marks;
arsort($marks_copy1);
echo "1. <strong>arsort()</strong> - Sort by values (descending):<br>";
foreach($marks_copy1 as $name => $mark) {
    echo "   $name: $mark<br>";
}

echo "<br>";

// Sort by keys (ascending)
$marks_copy2 = $marks;
ksort($marks_copy2);
echo "2. <strong>ksort()</strong> - Sort by keys (ascending):<br>";
foreach($marks_copy2 as $name => $mark) {
    echo "   $name: $mark<br>";
}

echo "<br>";

// Sort by keys (descending)
$marks_copy3 = $marks;
krsort($marks_copy3);
echo "3. <strong>krsort()</strong> - Sort by keys (descending):<br>";
foreach($marks_copy3 as $name => $mark) {
    echo "   $name: $mark<br>";
}

echo "<hr>";

// ===== PART (iv): Remove entry identified by key "Raj" =====
// Note: The question seems incomplete, assuming it asks to remove/delete the entry
echo "<h3>(iv) Remove Entry for 'Raj'</h3>";

echo "<strong>Before deletion:</strong><br>";
echo "<pre>";
print_r($marks);
echo "</pre>";

// Check if key exists before deletion
if(array_key_exists("Raj", $marks)) {
    echo "Entry for 'Raj' found: " . $marks["Raj"] . "<br>";

    // Delete the entry
    unset($marks["Raj"]);

    echo "Entry for 'Raj' has been deleted.<br>";
} else {
    echo "Entry for 'Raj' not found.<br>";
}

echo "<br><strong>After deletion:</strong><br>";
echo "<pre>";
print_r($marks);
echo "</pre>";

echo "<strong>Final Array Key-Value Pairs:</strong><br>";
foreach($marks as $name => $mark) {
    echo "$name: $mark<br>";
}

echo "<hr>";

// ===== COMPLETE DEMONSTRATION =====
echo "<h3>Complete Step-by-Step Summary</h3>";

// Reset the array
$marks = array("Ram" => 40, "Alice" => 20, "Raj" => 45, "Mary" => 35);

echo "<strong>Step 1 - Original Array:</strong><br>";
foreach($marks as $name => $mark) {
    echo "$name: $mark<br>";
}
echo "<br>";

echo "<strong>Step 2 - After modifying Ram to 50:</strong><br>";
$marks["Ram"] = 50;
foreach($marks as $name => $mark) {
    echo "$name: $mark<br>";
}
echo "<br>";

echo "<strong>Step 3 - After sorting by values:</strong><br>";
asort($marks);
foreach($marks as $name => $mark) {
    echo "$name: $mark<br>";
}
echo "<br>";

echo "<strong>Step 4 - After removing Raj:</strong><br>";
unset($marks["Raj"]);
foreach($marks as $name => $mark) {
    echo "$name: $mark<br>";
}

?>

Output Explanation:

Step 1: Original Array

Ram: 40
Alice: 20
Raj: 45
Mary: 35

Step 2: After Modification

Ram: 50    (changed from 40)
Alice: 20
Raj: 45
Mary: 35

Step 3: After Sorting (by values, ascending)

Alice: 20
Mary: 35
Raj: 45
Ram: 50

Step 4: After Removing "Raj"

Alice: 20
Mary: 35
Ram: 50

Summary of Array Functions Used:

Function Purpose Maintains Keys? Sort Order
asort() Sort by values, ascending Yes Ascending
arsort() Sort by values, descending Yes Descending
ksort() Sort by keys, ascending Yes Ascending
krsort() Sort by keys, descending Yes Descending
unset() Remove array element N/A N/A
array_key_exists() Check if key exists N/A N/A

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 17(b) - MARK DISTRIBUTION (Total: 8 marks)        │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Declare Associative Array (i)               │ 2 marks    │
│    - Array declaration with key-value pairs    │            │
│                                                │            │
│ 2. Modify Array Value (ii)                     │ 2 marks    │
│    - Syntax to update value by key             │            │
│                                                │            │
│ 3. Sort and Print Array (iii)                  │ 2 marks    │
│    - asort() function usage                    │            │
│    - foreach loop to print sorted pairs        │            │
│                                                │            │
│ 4. Remove Entry by Key (iv)                    │ 2 marks    │
│    - unset() function usage                    │            │
│    - Verification and output                   │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Four Equal Sub-parts (Section 3.2, Pattern 4)
Total: 6 marks (Part a) + 8 marks (Part b) = 14 marks

Question 18 (14 marks) — ---

Question 18(a) - 6 marks

Design an HTML form for entering a number by the user. Write a PHP code to display a message indicating whether the number is positive or negative when clicking on the submit button.

Answer:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Number Checker - Positive or Negative</title>
</head>
<body>
    <h2>Number Checker</h2>
    <p>Enter a number to check if it's positive or negative</p>

    <form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
        <label for="number">Enter a Number:</label><br>
        <input
            type="number"
            id="number"
            name="number"
            step="any"
            required
            placeholder="Enter any number"
        ><br><br>

        <button type="submit" name="submit">Check Number</button>
    </form>

    <?php
    // PHP code to process the form
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
        $number = $_POST['number'];

        if (is_numeric($number)) {
            $number = floatval($number);

            echo "<h3>Result:</h3>";
            if ($number > 0) {
                echo "<p>The number <strong>$number</strong> is <strong>POSITIVE</strong></p>";
            } elseif ($number < 0) {
                echo "<p>The number <strong>$number</strong> is <strong>NEGATIVE</strong></p>";
            } else {
                echo "<p>The number is <strong>ZERO</strong></p>";
            }
        }
    }
    ?>
</body>
</html>

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 18(a) - MARK DISTRIBUTION (Total: 6 marks)        │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. HTML Form Design                            │ 3 marks    │
│    - Form structure with method="POST"         │            │
│    - Number input field                        │            │
│    - Submit button                             │            │
│                                                │            │
│ 2. PHP Code for Positive/Negative Check        │ 3 marks    │
│    - Form data retrieval ($_POST)              │            │
│    - Validation (is_numeric check)             │            │
│    - Conditional logic for positive/negative   │            │
│    - Display appropriate message               │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Two Equal Components (Section 2.2, Pattern 1)

Question 18(b) - 8 marks

Write a PHP form handling program to perform the user registration of any website with a minimum of 5 different fields and insert the data into a MySQL table after establishing necessary connections with the Database.

Answer:

Database Setup (SQL):

CREATE DATABASE IF NOT EXISTS user_registration_db;
USE user_registration_db;

CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    full_name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    phone VARCHAR(15) NOT NULL,
    username VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    country VARCHAR(50) NOT NULL,
    registration_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

PHP Registration System:

<?php
// Database configuration
$servername = "localhost";
$db_username = "root";
$db_password = "";
$database = "user_registration_db";

// Create connection
$conn = mysqli_connect($servername, $db_username, $db_password, $database);

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

// Initialize variables
$full_name = $email = $phone = $username = $password = $country = "";
$errors = array();
$success = "";

// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['register'])) {

    // Get form data
    $full_name = mysqli_real_escape_string($conn, trim($_POST['full_name']));
    $email = mysqli_real_escape_string($conn, trim($_POST['email']));
    $phone = mysqli_real_escape_string($conn, trim($_POST['phone']));
    $username = mysqli_real_escape_string($conn, trim($_POST['username']));
    $password = mysqli_real_escape_string($conn, trim($_POST['password']));
    $country = mysqli_real_escape_string($conn, $_POST['country']);

    // Validation
    if (empty($full_name)) $errors[] = "Full name is required";
    if (empty($email)) $errors[] = "Email is required";
    if (empty($phone)) $errors[] = "Phone is required";
    if (empty($username)) $errors[] = "Username is required";
    if (empty($password)) $errors[] = "Password is required";
    if (empty($country)) $errors[] = "Country is required";

    // Check for duplicate email
    if (empty($errors)) {
        $check = "SELECT id FROM users WHERE email = '$email'";
        $result = mysqli_query($conn, $check);
        if (mysqli_num_rows($result) > 0) {
            $errors[] = "Email already exists";
        }
    }

    // Insert data if no errors
    if (empty($errors)) {
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);

        $sql = "INSERT INTO users (full_name, email, phone, username, password, country)
                VALUES ('$full_name', '$email', '$phone', '$username', '$hashed_password', '$country')";

        if (mysqli_query($conn, $sql)) {
            $success = "Registration successful!";
            $full_name = $email = $phone = $username = $password = $country = "";
        } else {
            $errors[] = "Error: " . mysqli_error($conn);
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User Registration</title>
</head>
<body>
    <h2>User Registration Form</h2>

    <?php
    if (!empty($errors)) {
        echo '<div><strong>Errors:</strong><ul>';
        foreach ($errors as $error) {
            echo "<li>$error</li>";
        }
        echo '</ul></div>';
    }

    if (!empty($success)) {
        echo '<p><strong>' . $success . '</strong></p>';
    }
    ?>

    <form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
        <label for="full_name">Full Name *</label><br>
        <input type="text" id="full_name" name="full_name"
               value="<?php echo htmlspecialchars($full_name); ?>" required><br><br>

        <label for="email">Email Address *</label><br>
        <input type="email" id="email" name="email"
               value="<?php echo htmlspecialchars($email); ?>" required><br><br>

        <label for="phone">Phone Number *</label><br>
        <input type="tel" id="phone" name="phone"
               value="<?php echo htmlspecialchars($phone); ?>" required><br><br>

        <label for="username">Username *</label><br>
        <input type="text" id="username" name="username"
               value="<?php echo htmlspecialchars($username); ?>" required><br><br>

        <label for="password">Password *</label><br>
        <input type="password" id="password" name="password" required><br><br>

        <label for="country">Country *</label><br>
        <select id="country" name="country" required>
            <option value="">-- Select Country --</option>
            <option value="India" <?php echo ($country == 'India') ? 'selected' : ''; ?>>India</option>
            <option value="USA" <?php echo ($country == 'USA') ? 'selected' : ''; ?>>USA</option>
            <option value="UK" <?php echo ($country == 'UK') ? 'selected' : ''; ?>>UK</option>
            <option value="Canada" <?php echo ($country == 'Canada') ? 'selected' : ''; ?>>Canada</option>
            <option value="Australia" <?php echo ($country == 'Australia') ? 'selected' : ''; ?>>Australia</option>
        </select><br><br>

        <button type="submit" name="register">Register Now</button>
    </form>
</body>
</html>

<?php mysqli_close($conn); ?>

Key Features:

Form Fields (6 fields - more than required 5):

  1. Full Name
  2. Email Address
  3. Phone Number
  4. Username
  5. Password
  6. Country (dropdown)

Database Operations:

  • MySQL connection establishment
  • Data validation
  • Duplicate email checking
  • Password hashing for security
  • Data insertion into users table

Security Features:

  • mysqli_real_escape_string() - Prevents SQL injection
  • password_hash() - Secures passwords
  • htmlspecialchars() - Prevents XSS attacks
  • Input validation and sanitization

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 18(b) - MARK DISTRIBUTION (Total: 8 marks)        │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Complete PHP User Registration Program     │ 8 marks    │
│    - HTML form with 5+ fields (name, email,   │            │
│      phone, username, password, etc.)          │            │
│    - MySQL database connection establishment   │            │
│    - Form data retrieval and validation        │            │
│    - SQL INSERT statement execution            │            │
│    - Error handling and security measures      │            │
│    - Password hashing (password_hash)          │            │
│    - SQL injection prevention                  │            │
│    - Success/error message display             │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Complete Program (Section 3.2, Pattern 5)
Total: 6 marks (Part a) + 8 marks (Part b) = 14 marks

PART B - Module V

Question 19 (14 marks) — ---

Question 19(a) - 6 marks

With a neat diagram, explain about Laravel MVC Framework

Answer:

Laravel MVC (Model-View-Controller) Framework

Laravel is a popular open-source PHP framework that follows the MVC (Model-View-Controller) architectural pattern. This pattern separates application logic into three interconnected components, promoting code organization, reusability, and maintainability.


Laravel MVC Architecture Diagram

┌─────────────────────────────────────────────────────────────────┐
│                         USER / BROWSER                          │
│                      (Sends HTTP Request)                       │
└────────────────────────────┬────────────────────────────────────┘
                             │
                             ▼
┌─────────────────────────────────────────────────────────────────┐
│                           ROUTER                                │
│                    (routes/web.php)                            │
│         Maps HTTP requests to appropriate Controller            │
└────────────────────────────┬────────────────────────────────────┘
                             │
                             ▼
┌─────────────────────────────────────────────────────────────────┐
│                         CONTROLLER                              │
│              (app/Http/Controllers/)                           │
│   • Receives user requests                                      │
│   • Processes input                                             │
│   • Interacts with Model                                        │
│   • Returns appropriate View                                    │
└──────────────┬────────────────────────────┬─────────────────────┘
               │                            │
               │                            │
               ▼                            ▼
┌──────────────────────────┐    ┌──────────────────────────┐
│         MODEL            │    │          VIEW            │
│  (app/Models/)          │    │   (resources/views/)    │
│                          │    │                          │
│ • Database interaction   │    │ • User interface         │
│ • Business logic         │    │ • Presentation layer     │
│ • Data validation        │◄───┤ • Blade templates        │
│ • Eloquent ORM          │    │ • HTML/CSS/JS            │
│                          │    │                          │
└──────────┬───────────────┘    └──────────┬───────────────┘
           │                               │
           │                               │
           ▼                               │
┌──────────────────────────┐              │
│       DATABASE           │              │
│  (MySQL, PostgreSQL)     │              │
│                          │              │
└──────────────────────────┘              │
                                          │
                ┌─────────────────────────┘
                │
                ▼
┌─────────────────────────────────────────────────────────────────┐
│                     HTTP RESPONSE                               │
│              (Sends HTML back to Browser)                       │
└─────────────────────────────────────────────────────────────────┘

Components of Laravel MVC

1. MODEL (M)

The Model represents the data layer of the application.

Location: app/Models/

Responsibilities:

  • Interacts with the database
  • Defines database table structure
  • Implements business logic and data validation
  • Uses Eloquent ORM for database operations

Example:

<?php
// app/Models/User.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'users';

    protected $fillable = ['name', 'email', 'password'];

    // Define relationships
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}
?>

2. VIEW (V)

The View handles the presentation layer and user interface.

Location: resources/views/

Responsibilities:

  • Displays data to users
  • Renders HTML using Blade templating engine
  • Contains no business logic
  • Receives data from Controller

Example:

<!-- resources/views/users/index.blade.php -->

<!DOCTYPE html>
<html>
<head>
    <title>Users List</title>
</head>
<body>
    <h1>All Users</h1>

    <table>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
        </tr>
        @foreach($users as $user)
        <tr>
            <td>{{ $user->id }}</td>
            <td>{{ $user->name }}</td>
            <td>{{ $user->email }}</td>
        </tr>
        @endforeach
    </table>
</body>
</html>

3. CONTROLLER (C)

The Controller acts as an intermediary between Model and View.

Location: app/Http/Controllers/

Responsibilities:

  • Receives and processes user requests
  • Retrieves data from Model
  • Passes data to View
  • Handles application logic
  • Returns HTTP responses

Example:

<?php
// app/Http/Controllers/UserController.php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index()
    {
        // Get all users from Model
        $users = User::all();

        // Pass data to View
        return view('users.index', ['users' => $users]);
    }

    public function show($id)
    {
        // Get specific user
        $user = User::findOrFail($id);

        return view('users.show', ['user' => $user]);
    }

    public function store(Request $request)
    {
        // Validate and save new user
        $validated = $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:6',
        ]);

        $user = User::create($validated);

        return redirect()->route('users.index');
    }
}
?>

Request-Response Flow in Laravel MVC

Step-by-Step Process:

  1. User sends HTTP request → Browser sends request to Laravel application
  2. Router intercepts → Routes file matches URL to Controller method
  3. Controller receives request → Processes incoming data
  4. Controller interacts with Model → Retrieves/updates database data
  5. Model queries Database → Executes database operations using Eloquent
  6. Database returns data → Results sent back to Model
  7. Model returns data to Controller → Structured data passed back
  8. Controller prepares View → Passes data to appropriate View template
  9. View renders HTML → Blade template processes data into HTML
  10. HTTP Response sent → Rendered HTML returned to user's browser

Benefits of Laravel MVC Architecture

1. Separation of Concerns:

  • Each component has a specific responsibility
  • Code is organized and maintainable

2. Code Reusability:

  • Models can be used across multiple Controllers
  • Views can be reused with different data

3. Parallel Development:

  • Frontend and backend developers can work simultaneously
  • Different team members can work on different components

4. Easy Testing:

  • Components can be tested independently
  • Unit testing is simplified

5. Scalability:

  • Easy to add new features without affecting existing code
  • Modular structure supports growth

6. Maintainability:

  • Changes in one component don't affect others
  • Debugging is easier due to clear separation

Laravel Directory Structure

laravel-project/
│
├── app/
│   ├── Http/
│   │   └── Controllers/        ← CONTROLLERS
│   └── Models/                 ← MODELS
│
├── resources/
│   └── views/                  ← VIEWS (Blade templates)
│
├── routes/
│   ├── web.php                 ← Web routes
│   └── api.php                 ← API routes
│
├── database/
│   ├── migrations/             ← Database schema
│   └── seeders/                ← Sample data
│
└── public/                     ← Entry point (index.php)

Summary

Laravel's MVC architecture provides:

  • Model: Data and business logic layer (Database interaction)
  • View: Presentation layer (User interface)
  • Controller: Application logic layer (Request handling)

This separation creates a robust, maintainable, and scalable application structure that is easy to develop and test.

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 19(a) - MARK DISTRIBUTION (Total: 6 marks)        │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Laravel MVC Diagram                         │ 2 marks    │
│    - Clear diagram showing M-V-C components    │            │
│    - Request-response flow visualization       │            │
│                                                │            │
│ 2. Laravel MVC Explanation                     │ 4 marks    │
│    - Model component and responsibilities      │            │
│    - View component and responsibilities       │            │
│    - Controller component and responsibilities │            │
│    - How components interact                   │            │
│    - Benefits of MVC architecture              │            │
│    - Laravel directory structure               │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Diagram + Detailed Explanation (Section 2.2, Pattern 6)

Question 19(b) - 8 marks

Discuss in detail about Laravel's Routing mechanisms

Answer:

Laravel Routing Mechanisms

Routing in Laravel is the mechanism that maps incoming HTTP requests to specific controller methods or closures. Routes are the entry points to your Laravel application and define how URLs are handled.


1. Basic Routing

Location: Routes are defined in:

  • routes/web.php - For web interface routes
  • routes/api.php - For API routes

Basic Syntax:

Route::method('uri', 'action');

Example:

<?php
// routes/web.php

use Illuminate\Support\Facades\Route;

// Simple route with closure
Route::get('/', function () {
    return view('welcome');
});

// Route returning text
Route::get('/hello', function () {
    return 'Hello, World!';
});

// Route with parameters
Route::get('/user/{id}', function ($id) {
    return 'User ID: ' . $id;
});
?>

2. HTTP Request Methods

Laravel supports all HTTP methods:

// GET request
Route::get('/posts', [PostController::class, 'index']);

// POST request
Route::post('/posts', [PostController::class, 'store']);

// PUT request
Route::put('/posts/{id}', [PostController::class, 'update']);

// PATCH request
Route::patch('/posts/{id}', [PostController::class, 'partialUpdate']);

// DELETE request
Route::delete('/posts/{id}', [PostController::class, 'destroy']);

// Match multiple methods
Route::match(['get', 'post'], '/form', function () {
    return 'GET or POST';
});

// Match any HTTP method
Route::any('/any', function () {
    return 'Any HTTP method';
});

3. Route Parameters

Required Parameters:

// Single parameter
Route::get('/user/{id}', function ($id) {
    return "User ID: $id";
});

// Multiple parameters
Route::get('/posts/{post}/comments/{comment}', function ($postId, $commentId) {
    return "Post: $postId, Comment: $commentId";
});

Optional Parameters:

// Optional parameter with default value
Route::get('/user/{name?}', function ($name = 'Guest') {
    return "Hello, $name";
});

Regular Expression Constraints:

// Numeric only
Route::get('/user/{id}', function ($id) {
    return "User: $id";
})->where('id', '[0-9]+');

// Alphabetic only
Route::get('/user/{name}', function ($name) {
    return "User: $name";
})->where('name', '[A-Za-z]+');

// Multiple constraints
Route::get('/user/{id}/{name}', function ($id, $name) {
    return "ID: $id, Name: $name";
})->where(['id' => '[0-9]+', 'name' => '[A-Za-z]+']);

4. Named Routes

Named routes allow convenient generation of URLs and redirects.

Defining Named Routes:

// Using name() method
Route::get('/profile', [ProfileController::class, 'show'])->name('profile');

// Using array syntax
Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');

Using Named Routes:

// Generate URL
$url = route('profile');

// Generate URL with parameters
$url = route('user.profile', ['id' => 1]);
// Result: /user/1/profile

// Redirect to named route
return redirect()->route('dashboard');

// Redirect with parameters
return redirect()->route('user.profile', ['id' => $userId]);

In Blade Templates:

<!-- Generate link to named route -->
<a href="{{ route('profile') }}">View Profile</a>

<!-- With parameters -->
<a href="{{ route('user.show', ['id' => $user->id]) }}">View User</a>

5. Route Groups

Route groups allow sharing attributes across multiple routes.

Basic Grouping:

Route::prefix('admin')->group(function () {
    Route::get('/users', function () {
        // Matches: /admin/users
    });

    Route::get('/posts', function () {
        // Matches: /admin/posts
    });
});

Middleware Grouping:

Route::middleware(['auth', 'verified'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
    Route::get('/profile', [ProfileController::class, 'show']);
});

Namespace Grouping:

Route::namespace('Admin')->group(function () {
    // Controllers within "App\Http\Controllers\Admin" namespace
    Route::get('/dashboard', [DashboardController::class, 'index']);
});

Combining Multiple Attributes:

Route::prefix('admin')
    ->middleware('auth')
    ->name('admin.')
    ->group(function () {
        Route::get('/users', [UserController::class, 'index'])->name('users');
        // Name: admin.users, URL: /admin/users
    });

6. Resource Routes

Resource routes provide CRUD operations automatically.

Single Resource:

Route::resource('posts', PostController::class);

This creates the following routes:

HTTP Method URI Action Route Name
GET /posts index posts.index
GET /posts/create create posts.create
POST /posts store posts.store
GET /posts/{post} show posts.show
GET /posts/{post}/edit edit posts.edit
PUT/PATCH /posts/{post} update posts.update
DELETE /posts/{post} destroy posts.destroy

Partial Resource:

// Only specific methods
Route::resource('posts', PostController::class)->only(['index', 'show']);

// Exclude specific methods
Route::resource('posts', PostController::class)->except(['destroy']);

API Resource:

// Excludes create and edit methods
Route::apiResource('posts', PostController::class);

Multiple Resources:

Route::resources([
    'posts' => PostController::class,
    'comments' => CommentController::class,
]);

7. Route Model Binding

Implicit Binding:

// Route definition
Route::get('/users/{user}', [UserController::class, 'show']);

// Controller method
public function show(User $user)
{
    // Laravel automatically retrieves the User model
    return view('users.show', ['user' => $user]);
}

Explicit Binding:

// In RouteServiceProvider
public function boot()
{
    Route::model('user', User::class);
}

// Route
Route::get('/profile/{user}', function (User $user) {
    return $user;
});

8. Route Caching

For production environments, route caching improves performance.

Cache Routes:

php artisan route:cache

Clear Route Cache:

php artisan route:clear

View Routes:

php artisan route:list

9. Fallback Routes

Handle undefined routes:

Route::fallback(function () {
    return view('errors.404');
});

10. Redirect Routes

Simple Redirects:

Route::redirect('/old-url', '/new-url');

// With status code
Route::redirect('/old-url', '/new-url', 301);

// Permanent redirect
Route::permanentRedirect('/old-url', '/new-url');

11. Subdomain Routing

Route::domain('{account}.example.com')->group(function () {
    Route::get('/user/{id}', function ($account, $id) {
        return "Account: $account, User: $id";
    });
});

12. Rate Limiting

Protect routes from excessive requests:

Route::middleware('throttle:60,1')->group(function () {
    Route::get('/api/users', [UserController::class, 'index']);
});
// 60 requests per minute

Complete Routing Example

<?php
// routes/web.php

use App\Http\Controllers\PostController;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;

// Simple routes
Route::get('/', function () {
    return view('welcome');
});

// Controller routes
Route::get('/about', [PageController::class, 'about'])->name('about');

// Resource routes
Route::resource('posts', PostController::class);

// Route with parameters
Route::get('/user/{id}', [UserController::class, 'show'])
    ->where('id', '[0-9]+')
    ->name('user.show');

// Route groups
Route::prefix('admin')->middleware('auth')->name('admin.')->group(function () {
    Route::get('/dashboard', [AdminController::class, 'dashboard'])->name('dashboard');
    Route::resource('users', AdminUserController::class);
});

// API routes
Route::prefix('api')->middleware('api')->group(function () {
    Route::apiResource('posts', PostController::class);
});

// Fallback
Route::fallback(function () {
    return view('errors.404');
});
?>

Summary

Laravel's routing system provides:

  1. Flexible URL mapping to controllers and closures
  2. Multiple HTTP method support (GET, POST, PUT, DELETE, etc.)
  3. Route parameters with constraints
  4. Named routes for easy URL generation
  5. Route groups for organization
  6. Resource routes for CRUD operations
  7. Route model binding for automatic model injection
  8. Middleware integration for authentication and authorization
  9. Performance optimization through route caching

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 19(b) - MARK DISTRIBUTION (Total: 8 marks)        │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Laravel Routing Mechanisms Detailed Discussion│ 8 marks  │
│    - Basic route definition and syntax         │            │
│    - HTTP verb-based routing (GET, POST, etc.) │            │
│    - Route parameters (required & optional)    │            │
│    - Named routes and usage                    │            │
│    - Route groups and prefixes                 │            │
│    - Resource routing and REST operations      │            │
│    - Route model binding                       │            │
│    - Middleware and route protection           │            │
│    - Route caching and optimization            │            │
│    - Comprehensive code examples               │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Comprehensive Discussion (Section 3.2, Pattern 5)
Total: 6 marks (Part a) + 8 marks (Part b) = 14 marks

Question 20 (14 marks) — ---

Question 20(a) - 8 marks

List the data types used in JSON? Explain the use of parse() and stringify() functions in JSON with examples.

Answer:

JSON Data Types

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate.


1. Data Types in JSON

JSON supports 6 fundamental data types:

1. String

  • Text enclosed in double quotes
  • Supports Unicode characters
{
    "name": "John Doe",
    "email": "john@example.com",
    "message": "Hello, World!"
}

2. Number

  • Integer or floating-point
  • No quotes required
  • Can be positive, negative, or decimal
{
    "age": 25,
    "price": 99.99,
    "temperature": -15.5,
    "quantity": 100
}

3. Boolean

  • Two values: true or false
  • Lowercase only (not quoted)
{
    "isActive": true,
    "hasAccess": false,
    "verified": true
}

4. Null

  • Represents empty or non-existent value
  • Written as null (lowercase, not quoted)
{
    "middleName": null,
    "spouse": null
}

5. Array

  • Ordered list of values
  • Enclosed in square brackets []
  • Values separated by commas
  • Can contain any data type
{
    "colors": ["red", "green", "blue"],
    "numbers": [1, 2, 3, 4, 5],
    "mixed": [1, "text", true, null],
    "nested": [[1, 2], [3, 4]]
}

6. Object

  • Collection of key-value pairs
  • Enclosed in curly braces {}
  • Keys must be strings in double quotes
  • Values can be any JSON data type
{
    "person": {
        "name": "Alice",
        "age": 30,
        "address": {
            "city": "New York",
            "country": "USA"
        }
    }
}

Complete Example with All Data Types

{
    "string": "Hello World",
    "number": 42,
    "float": 3.14159,
    "boolean": true,
    "nullValue": null,
    "array": [1, 2, 3, 4, 5],
    "object": {
        "key1": "value1",
        "key2": "value2"
    },
    "mixedArray": [
        "text",
        123,
        true,
        null,
        {"nested": "object"}
    ]
}

2. JSON.parse() Function

Purpose: Converts a JSON string into a JavaScript object.

Syntax:

JSON.parse(jsonString[, reviver])

Parameters:

  • jsonString: The JSON string to parse
  • reviver (optional): Function to transform results

Example 1: Basic Parsing

// JSON string
const jsonString = '{"name": "John", "age": 30, "city": "New York"}';

// Parse JSON string to JavaScript object
const person = JSON.parse(jsonString);

console.log(person.name);  // Output: John
console.log(person.age);   // Output: 30
console.log(person.city);  // Output: New York

Example 2: Parsing Arrays

// JSON array string
const jsonArray = '[1, 2, 3, 4, 5]';

// Parse to JavaScript array
const numbers = JSON.parse(jsonArray);

console.log(numbers);       // Output: [1, 2, 3, 4, 5]
console.log(numbers[0]);    // Output: 1
console.log(numbers.length); // Output: 5

Example 3: Parsing Nested Objects

const jsonData = `{
    "student": {
        "name": "Alice",
        "grades": [85, 90, 78],
        "active": true
    }
}`;

const data = JSON.parse(jsonData);

console.log(data.student.name);      // Output: Alice
console.log(data.student.grades[1]); // Output: 90
console.log(data.student.active);    // Output: true

Example 4: Using Reviver Function

const jsonString = '{"name": "Bob", "age": "25", "date": "2024-01-15"}';

// Reviver function to transform values
const person = JSON.parse(jsonString, (key, value) => {
    // Convert age string to number
    if (key === 'age') {
        return parseInt(value);
    }
    // Convert date string to Date object
    if (key === 'date') {
        return new Date(value);
    }
    return value;
});

console.log(person.age);        // Output: 25 (number)
console.log(person.date);       // Output: Date object
console.log(typeof person.age); // Output: number

Example 5: Handling Parse Errors

const invalidJSON = '{name: "John"}'; // Invalid: keys not in quotes

try {
    const obj = JSON.parse(invalidJSON);
} catch (error) {
    console.error('Parse error:', error.message);
    // Output: Parse error: Unexpected token n in JSON at position 1
}

3. JSON.stringify() Function

Purpose: Converts a JavaScript object into a JSON string.

Syntax:

JSON.stringify(value[, replacer[, space]])

Parameters:

  • value: The JavaScript value to convert
  • replacer (optional): Function or array to filter properties
  • space (optional): Adds indentation for readability

Example 1: Basic Stringification

// JavaScript object
const person = {
    name: "John Doe",
    age: 30,
    city: "New York"
};

// Convert to JSON string
const jsonString = JSON.stringify(person);

console.log(jsonString);
// Output: {"name":"John Doe","age":30,"city":"New York"}

Example 2: Stringifying Arrays

const numbers = [1, 2, 3, 4, 5];
const jsonArray = JSON.stringify(numbers);

console.log(jsonArray);  // Output: [1,2,3,4,5]

Example 3: Pretty Printing with Indentation

const person = {
    name: "Alice",
    age: 25,
    address: {
        city: "Boston",
        country: "USA"
    }
};

// Add indentation (2 spaces)
const prettyJSON = JSON.stringify(person, null, 2);

console.log(prettyJSON);
/*
Output:
{
  "name": "Alice",
  "age": 25,
  "address": {
    "city": "Boston",
    "country": "USA"
  }
}
*/

Example 4: Using Replacer Function

const user = {
    username: "john_doe",
    password: "secret123",
    email: "john@example.com",
    age: 30
};

// Filter out password field
const jsonString = JSON.stringify(user, (key, value) => {
    if (key === 'password') {
        return undefined; // Exclude this property
    }
    return value;
});

console.log(jsonString);
// Output: {"username":"john_doe","email":"john@example.com","age":30}

Example 5: Using Replacer Array

const person = {
    name: "Bob",
    age: 28,
    email: "bob@example.com",
    password: "secret"
};

// Only include specific properties
const jsonString = JSON.stringify(person, ['name', 'email']);

console.log(jsonString);
// Output: {"name":"Bob","email":"bob@example.com"}

4. Practical Examples: parse() and stringify() Together

Example 1: Deep Copy of Object

const original = {
    name: "Alice",
    scores: [85, 90, 78]
};

// Create deep copy using JSON methods
const copy = JSON.parse(JSON.stringify(original));

copy.scores[0] = 100;

console.log(original.scores); // [85, 90, 78] - unchanged
console.log(copy.scores);     // [100, 90, 78] - modified

Example 2: LocalStorage Integration

// Save object to localStorage
const user = {
    id: 1,
    name: "John",
    preferences: {
        theme: "dark",
        language: "en"
    }
};

// Convert to JSON string and save
localStorage.setItem('user', JSON.stringify(user));

// Retrieve and parse back to object
const savedUser = JSON.parse(localStorage.getItem('user'));

console.log(savedUser.preferences.theme); // Output: dark

Example 3: API Data Handling

// Sending data to API
const formData = {
    username: "alice",
    email: "alice@example.com",
    age: 25
};

// Convert to JSON for sending
const jsonData = JSON.stringify(formData);

// Simulate API response
const apiResponse = '{"status":"success","userId":123}';

// Parse API response
const response = JSON.parse(apiResponse);
console.log(response.userId); // Output: 123

Comparison Table

Feature JSON.parse() JSON.stringify()
Purpose Convert JSON string to object Convert object to JSON string
Input JSON string JavaScript object/array
Output JavaScript object/array JSON string
Use Case Receiving API data Sending API data
Error Handling Throws error on invalid JSON Generally safe

Summary

JSON Data Types:

  1. String
  2. Number
  3. Boolean
  4. Null
  5. Array
  6. Object

JSON.parse():

  • Converts JSON string → JavaScript object
  • Used for reading/receiving data
  • Can use reviver function for transformations

JSON.stringify():

  • Converts JavaScript object → JSON string
  • Used for sending/storing data
  • Can use replacer for filtering
  • Can add formatting with space parameter

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 20(a) - MARK DISTRIBUTION (Total: 8 marks)        │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. JSON Data Types                             │ 3 marks    │
│    - String, Number, Boolean types             │            │
│    - Null, Array, Object types                 │            │
│    - Examples for each data type               │            │
│                                                │            │
│ 2. JSON.parse() Function                       │ 2.5 marks  │
│    - Purpose and syntax                        │            │
│    - Converting JSON string to object          │            │
│    - Working examples with explanation         │            │
│                                                │            │
│ 3. JSON.stringify() Function                   │ 2.5 marks  │
│    - Purpose and syntax                        │            │
│    - Converting object to JSON string          │            │
│    - Working examples with parameters          │            │
│    - Comparison with JSON.parse()              │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Three Components (Section 3.2, Pattern 2)

Question 20(b) - 6 marks

What is Route Model Binding in Laravel? Which types of route model binding are supported in Laravel?

Answer:

Route Model Binding in Laravel

Route Model Binding is a Laravel feature that automatically injects model instances into route callbacks or controller methods based on route parameters. Instead of manually querying the database, Laravel automatically retrieves the model instance for you.


Benefits of Route Model Binding

  1. Code Simplification: Reduces boilerplate code
  2. Automatic 404 Handling: Throws ModelNotFoundException if not found
  3. Type Safety: Ensures correct model type
  4. Cleaner Code: More readable and maintainable

Types of Route Model Binding

Laravel supports two types of route model binding:

  1. Implicit Binding
  2. Explicit Binding

1. Implicit Route Model Binding

Definition: Laravel automatically resolves model instances based on type-hinted variable names that match route segment names.

How it Works:

  • Route parameter name matches the variable name in controller method
  • Variable is type-hinted with the model class
  • Laravel automatically queries the database using the route parameter

Example 1: Basic Implicit Binding

Without Route Model Binding:

// Route
Route::get('/users/{id}', [UserController::class, 'show']);

// Controller
public function show($id)
{
    $user = User::findOrFail($id); // Manual query
    return view('users.show', ['user' => $user]);
}

With Implicit Binding:

// Route
Route::get('/users/{user}', [UserController::class, 'show']);

// Controller
use App\Models\User;

public function show(User $user)  // Type-hint with model
{
    // $user is automatically injected
    return view('users.show', ['user' => $user]);
}

Example 2: Multiple Model Bindings

// Route
Route::get('/posts/{post}/comments/{comment}',
    [CommentController::class, 'show']);

// Controller
use App\Models\Post;
use App\Models\Comment;

public function show(Post $post, Comment $comment)
{
    // Both models automatically injected
    return view('comments.show', [
        'post' => $post,
        'comment' => $comment
    ]);
}

Example 3: Customizing the Key

By default, Laravel uses the id column. You can customize this:

// In the Model
class User extends Model
{
    // Use 'slug' instead of 'id'
    public function getRouteKeyName()
    {
        return 'slug';
    }
}

// Route
Route::get('/users/{user}', [UserController::class, 'show']);
// Now it will query: SELECT * FROM users WHERE slug = ?

// Controller
public function show(User $user)
{
    // $user retrieved by slug
    return view('users.show', ['user' => $user]);
}

Example 4: Soft Deleted Models

// Include soft deleted models
Route::get('/users/{user}', [UserController::class, 'show'])
    ->withTrashed();

// Controller
public function show(User $user)
{
    // Will include soft-deleted users
    return view('users.show', ['user' => $user]);
}

Example 5: Scoped Binding

Automatically scope child models to parent:

// Route - ensure comment belongs to post
Route::get('/posts/{post}/comments/{comment:id}',
    [CommentController::class, 'show'])->scopeBindings();

// Controller
public function show(Post $post, Comment $comment)
{
    // Comment is automatically scoped to the post
    // Laravel ensures: comment->post_id === post->id
    return view('comments.show', [
        'post' => $post,
        'comment' => $comment
    ]);
}

2. Explicit Route Model Binding

Definition: Manually define how Laravel should resolve model instances for specific route parameters.

Configuration Location: App\Providers\RouteServiceProviderboot() method


Example 1: Basic Explicit Binding

// app/Providers/RouteServiceProvider.php

use App\Models\User;
use Illuminate\Support\Facades\Route;

public function boot()
{
    // Bind 'user' parameter to User model
    Route::model('user', User::class);

    parent::boot();
}

// Route
Route::get('/profile/{user}', function (User $user) {
    return $user;
});

Example 2: Custom Resolution Logic

// app/Providers/RouteServiceProvider.php

use App\Models\User;

public function boot()
{
    // Custom resolution by email
    Route::bind('user', function ($value) {
        return User::where('email', $value)->firstOrFail();
    });

    parent::boot();
}

// Route
Route::get('/users/{user}', [UserController::class, 'show']);
// Now matches by email: /users/john@example.com

Example 3: Complex Custom Logic

public function boot()
{
    Route::bind('post', function ($value) {
        // Try to find by ID first
        if (is_numeric($value)) {
            return Post::findOrFail($value);
        }

        // Otherwise, find by slug
        return Post::where('slug', $value)->firstOrFail();
    });
}

// Route works with both:
// /posts/123 (by ID)
// /posts/my-post-slug (by slug)

Example 4: Binding with Relationships

public function boot()
{
    Route::bind('comment', function ($value) {
        return Comment::with('post', 'user')->findOrFail($value);
    });
}

// Controller
public function show(Comment $comment)
{
    // $comment already has post and user relationships loaded
    return view('comments.show', ['comment' => $comment]);
}

Comparison: Implicit vs Explicit Binding

Aspect Implicit Binding Explicit Binding
Configuration None required Requires RouteServiceProvider
Flexibility Limited customization Full control over resolution
Default Behavior Uses primary key (id) Custom logic possible
Setup Complexity Simple More complex
Use Case Standard CRUD operations Custom resolution logic
Example Auto-resolve by ID Resolve by slug, email, etc.

Complete Practical Example

Scenario: Blog application with posts and comments

Models:

// app/Models/Post.php
class Post extends Model
{
    public function getRouteKeyName()
    {
        return 'slug'; // Use slug instead of id
    }

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

// app/Models/Comment.php
class Comment extends Model
{
    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

Routes:

// routes/web.php

// Implicit binding with slug
Route::get('/posts/{post}', [PostController::class, 'show'])
    ->name('posts.show');

// Scoped binding - comment must belong to post
Route::get('/posts/{post}/comments/{comment}',
    [CommentController::class, 'show'])
    ->scopeBindings()
    ->name('comments.show');

Controllers:

// app/Http/Controllers/PostController.php
class PostController extends Controller
{
    public function show(Post $post)
    {
        // Post automatically retrieved by slug
        return view('posts.show', ['post' => $post]);
    }
}

// app/Http/Controllers/CommentController.php
class CommentController extends Controller
{
    public function show(Post $post, Comment $comment)
    {
        // Both models injected
        // Comment automatically scoped to post
        return view('comments.show', [
            'post' => $post,
            'comment' => $comment
        ]);
    }
}

Advanced Features

1. Fallback Routes:

Route::get('/users/{user}', function (User $user) {
    return $user;
})->missing(function (Request $request) {
    return Redirect::route('users.index');
});

2. Enum Binding (Laravel 9+):

Route::get('/posts/{category}', function (Category $category) {
    // Category is an enum
    return $category;
});

Summary

Route Model Binding automatically injects model instances based on route parameters.

Two Types:

1. Implicit Binding:

  • Automatic resolution by parameter name
  • Default uses primary key (id)
  • Can customize with getRouteKeyName()
  • Supports scoped bindings
  • Simple and convenient

2. Explicit Binding:

  • Manual configuration in RouteServiceProvider
  • Full control over resolution logic
  • Can use custom columns (slug, email, etc.)
  • Complex conditional logic possible
  • More flexible but requires setup

Both approaches eliminate boilerplate code and provide automatic 404 handling when models are not found.

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 20(b) - MARK DISTRIBUTION (Total: 6 marks)        │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Route Model Binding Definition              │ 2 marks    │
│    - What is Route Model Binding               │            │
│    - Purpose and benefits                      │            │
│                                                │            │
│ 2. Implicit Binding                            │ 2 marks    │
│    - How implicit binding works                │            │
│    - Automatic model resolution                │            │
│    - Code examples and customization           │            │
│                                                │            │
│ 3. Explicit Binding                            │ 2 marks    │
│    - How explicit binding works                │            │
│    - Manual configuration in RouteServiceProvider│           │
│    - Code examples and use cases               │            │
│    - Comparison with implicit binding          │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Definition + Two Types (Section 2.2, Pattern 2)
Total: 8 marks (Part a) + 6 marks (Part b) = 14 marks