CST463 Web Programming - Solved Papers

CST463 Web Programming - Answer Key

CST463 Web Programming - Answer Key

CST463 Web Programming - Answer Key

December 2023 Examination (2019 Scheme)

Subject: Web Programming (CST463)
Date: December 2023
Total Marks: 100
Duration: 3 Hours
Examination: Seventh Semester B.Tech Degree Regular and Supplementary Examination


PART A (Short Answer Questions)

Answer all questions, each carries 3 marks

Question 1 (3 marks) — Write the structure of HTML with example.

Write the structure of HTML with example.

Answer:

An HTML document follows a hierarchical structure with nested elements. The basic structure includes the document type declaration, root element, head section for metadata, and body section for visible content.

Basic HTML Structure:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My First Webpage</title>
</head>
<body>
    <h1>Welcome to HTML</h1>
    <p>This is a paragraph of text.</p>
</body>
</html>

Key Components:

  • <!DOCTYPE html>: Declares HTML5 document type
  • <html>: Root element that contains all other elements
  • <head>: Contains metadata, title, and links to resources
  • <body>: Contains all visible content displayed in the browser

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 1 - MARK DISTRIBUTION (Total: 3 marks)            │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. HTML Structure Explanation                  │ 1.5 marks  │
│    - Hierarchical structure description        │            │
│    - Key components identification             │            │
│                                                │            │
│ 2. Complete HTML Example                       │ 1.5 marks  │
│    - DOCTYPE declaration                       │            │
│    - <html>, <head>, <body> structure          │            │
│    - Meta tags and title                       │            │
│    - Content elements (h1, p)                  │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Explanation + Example (Section 1.2, Pattern 2)

Question 2 (3 marks) — What is a URL? Explain the different parts of URL with example.

What is a URL? Explain the different parts of URL with example.

Answer:

A URL (Uniform Resource Locator) is a unique address used to locate resources on the internet. It specifies the location of a web page, file, or other resource and the protocol to access it.

Parts of a URL:

Example: https://www.example.com:8080/path/page.html?id=123&name=test#section2

  1. Protocol (https://): Specifies how to access the resource (HTTP, HTTPS, FTP)
  2. Domain Name (www.example.com): Identifies the server hosting the resource
  3. Port Number (:8080): Specifies the communication port (optional, defaults: 80 for HTTP, 443 for HTTPS)
  4. Path (/path/page.html): Location of the resource on the server
  5. Query String (?id=123&name=test): Parameters passed to the resource
  6. Fragment (#section2): Specific section within the page

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 2 - MARK DISTRIBUTION (Total: 3 marks)            │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Definition of URL                           │ 1 mark     │
│    - Explanation of what URL is                │            │
│    - Purpose of URL                            │            │
│                                                │            │
│ 2. Different Parts of URL with Example         │ 2 marks    │
│    - Complete URL example                      │            │
│    - Protocol explanation                      │            │
│    - Domain name explanation                   │            │
│    - Port number explanation                   │            │
│    - Path explanation                          │            │
│    - Query string explanation                  │            │
│    - Fragment explanation                      │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Definition + Explanation with Example (Section 1.2, Pattern 2)

Question 3 (3 marks) — Explain id selector and class selector in CSS with suitable examples.

Explain id selector and class selector in CSS with suitable examples.

Answer:

CSS selectors are used to target HTML elements for styling. ID and class selectors are two important types that allow precise element selection.

ID Selector:

  • Uses hash symbol # followed by the ID name
  • Targets a single unique element
  • Should be unique within a page
#header {
    background-color: blue;
    color: white;
}
<div id="header">This is the header</div>

Class Selector:

  • Uses dot . followed by the class name
  • Can be applied to multiple elements
  • Reusable across different elements
.highlight {
    background-color: yellow;
    font-weight: bold;
}
<p class="highlight">Highlighted paragraph 1</p>
<p class="highlight">Highlighted paragraph 2</p>

Key Difference: ID is unique (used once), class is reusable (used multiple times).

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 3 - MARK DISTRIBUTION (Total: 3 marks)            │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. ID Selector Explanation                     │ 1.5 marks  │
│    - Syntax with # symbol                      │            │
│    - Characteristics (unique, single element)  │            │
│    - CSS and HTML example                      │            │
│                                                │            │
│ 2. Class Selector Explanation                  │ 1.5 marks  │
│    - Syntax with . symbol                      │            │
│    - Characteristics (reusable, multiple)      │            │
│    - CSS and HTML example                      │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Differentiate Two Concepts (Section 1.2, Pattern 1)

Question 4 (3 marks) — Explain array creation in JavaScript with examples.

Explain array creation in JavaScript with examples.

Answer:

JavaScript provides multiple ways to create arrays. An array is a special variable that can hold multiple values under a single name with indexed access.

Methods to Create Arrays:

1. Array Literal (Most Common):

let fruits = ["Apple", "Banana", "Orange"];
let numbers = [1, 2, 3, 4, 5];
let mixed = [1, "Hello", true, null];

2. Array Constructor:

let colors = new Array("Red", "Green", "Blue");
let emptyArray = new Array(5); // Creates array with 5 empty slots

3. Array.of() Method:

let items = Array.of(10, 20, 30);

4. Array.from() Method:

let str = "Hello";
let charArray = Array.from(str); // ['H', 'e', 'l', 'l', 'o']

Accessing Array Elements:

console.log(fruits[0]); // Output: Apple
console.log(fruits.length); // Output: 3

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 4 - MARK DISTRIBUTION (Total: 3 marks)            │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Array Concept and Creation Methods          │ 1.5 marks  │
│    - Definition of arrays                      │            │
│    - Array literal syntax                      │            │
│    - Array constructor                         │            │
│                                                │            │
│ 2. Additional Methods and Usage                │ 1.5 marks  │
│    - Array.of() method                         │            │
│    - Array.from() method                       │            │
│    - Accessing array elements                  │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Explanation + Examples (Section 1.2, Pattern 2)

Question 5 (3 marks) — How to use functions in a PHP program with an example.

How to use functions in a PHP program with an example.

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 Syntax:

function functionName($parameter1, $parameter2) {
    // Function body
    return $result;
}

Example - Function to Calculate Area of Rectangle:

<?php
// Function definition
function calculateArea($length, $width) {
    $area = $length * $width;
    return $area;
}

// Function call
$result = calculateArea(10, 5);
echo "Area of rectangle: " . $result; // Output: Area of rectangle: 50

// Function with default parameter
function greet($name = "Guest") {
    return "Hello, " . $name . "!";
}

echo greet("John");  // Output: Hello, John!
echo greet();        // Output: Hello, Guest!
?>

Key Points:

  • Functions are defined using the function keyword
  • Can accept parameters and return values
  • Can have default parameter values
  • Called by name followed by parentheses

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 5 - MARK DISTRIBUTION (Total: 3 marks)            │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Function Syntax and Explanation             │ 1.5 marks  │
│    - Function definition syntax                │            │
│    - Purpose and benefits of functions         │            │
│                                                │            │
│ 2. Practical Examples with Code                │ 1.5 marks  │
│    - calculateArea() function example          │            │
│    - greet() function with default parameters  │            │
│    - Function calls and outputs                │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Explanation + Examples (Section 1.2, Pattern 2)

Question 6 (3 marks) — Distinguish between implode and explode function in PHP with suitable examples.

Distinguish between implode and explode function in PHP with suitable examples.

Answer:

Both implode() and explode() are PHP functions that convert between strings and arrays, but they work in opposite directions.

explode() Function:

  • Converts a string into an array
  • Splits a string by a specified delimiter
  • Syntax: explode(separator, string, limit)
<?php
$str = "Apple,Banana,Orange";
$fruits = explode(",", $str);
print_r($fruits);
// Output: Array ( [0] => Apple [1] => Banana [2] => Orange )
?>

implode() Function:

  • Converts an array into a string
  • Joins array elements with a specified separator
  • Syntax: implode(separator, array)
<?php
$colors = array("Red", "Green", "Blue");
$str = implode(", ", $colors);
echo $str;
// Output: Red, Green, Blue
?>

Key Difference:

  • explode(): String → Array (splits)
  • implode(): Array → String (joins)

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 6 - MARK DISTRIBUTION (Total: 3 marks)            │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. explode() Function                          │ 1.5 marks  │
│    - Purpose (string to array conversion)      │            │
│    - Syntax explanation                        │            │
│    - Complete example with output              │            │
│                                                │            │
│ 2. implode() Function                          │ 1.5 marks  │
│    - Purpose (array to string conversion)      │            │
│    - Syntax explanation                        │            │
│    - Complete example with output              │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Differentiate Two Concepts (Section 1.2, Pattern 1)

Question 7 (3 marks) — What is cookie? How does PHP support the concept of cookies.

What is cookie? How does PHP support the concept of cookies.

Answer:

A cookie is a small piece of data stored on the client's browser by the web server. Cookies are used to remember information about the user across multiple page requests or visits.

Uses of Cookies:

  • User authentication and session tracking
  • Storing user preferences
  • Shopping cart data
  • Tracking user behavior

PHP Cookie Support:

PHP provides the setcookie() function to create and manage cookies.

Syntax:

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

Example:

<?php
// Setting a cookie
setcookie("username", "John", time() + (86400 * 30), "/"); // 86400 = 1 day

// Accessing a cookie
if(isset($_COOKIE["username"])) {
    echo "Welcome " . $_COOKIE["username"];
}

// Deleting a cookie (set expiry to past time)
setcookie("username", "", time() - 3600, "/");
?>

Key Points:

  • Cookies must be set before any HTML output
  • Stored on client side, accessible via $_COOKIE superglobal array
  • Have expiration time and security options

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 7 - MARK DISTRIBUTION (Total: 3 marks)            │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Cookie Concept and PHP Support               │ 1.5 marks  │
│    - Definition of cookies                     │            │
│    - Uses of cookies                           │            │
│    - setcookie() function syntax               │            │
│                                                │            │
│ 2. PHP Cookie Examples                         │ 1.5 marks  │
│    - Setting a cookie with parameters          │            │
│    - Accessing cookie with $_COOKIE            │            │
│    - Deleting a cookie                         │            │
│    - Key points about cookie usage             │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Explanation + Examples (Section 1.2, Pattern 2)

Question 8 (3 marks) — Write a simple connection script to make a connection to MYSQL with PHP.

Write a simple connection script to make a connection to MYSQL with PHP.

Answer:

PHP provides PDO (PHP Data Objects) for secure database connections. PDO is the modern, recommended approach for database interactions.

PDO Connection Script:

<?php
try {
    // Database configuration
    $host = "localhost";
    $dbname = "mydatabase";
    $username = "root";
    $password = "";

    // DSN (Data Source Name)
    $dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4";

    // PDO options
    $options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ];

    // Create PDO connection
    $pdo = new PDO($dsn, $username, $password, $options);

    echo "Connected successfully to MySQL database!";

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

Key Features:

  • Uses PDO for database-independent connection
  • Exception handling with try-catch block
  • Proper error mode configuration for debugging
  • Secure connection with UTF-8 character set

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 8 - MARK DISTRIBUTION (Total: 3 marks)            │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ Complete MySQL Connection Script               │ 3 marks    │
│    - Database configuration variables          │            │
│    - DSN string construction                   │            │
│    - PDO options configuration                 │            │
│    - PDO connection creation                   │            │
│    - Exception handling with try-catch         │            │
│    - Success/error messages                    │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Complete Programming Solution (Section 1.2, Pattern 5)

Question 9 (3 marks) — Briefly explain JSON syntax with example.

Briefly explain JSON syntax with example.

Answer:

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.

JSON Syntax Rules:

  • Data is in name/value pairs: "name": "value"
  • Data is separated by commas
  • Curly braces {} hold objects
  • Square brackets [] hold arrays
  • Uses double quotes for strings

Example:

{
    "student": {
        "name": "John Doe",
        "age": 21,
        "enrolled": true,
        "courses": ["Web Programming", "Database", "AI"],
        "address": {
            "city": "Delhi",
            "pincode": "110001"
        },
        "marks": null
    }
}

Key Points:

  • Supports data types: string, number, boolean, object, array, null
  • Keys must be strings in double quotes
  • Values can be any valid JSON data type
  • No comments allowed in JSON
  • Widely used for data exchange between client and server

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 9 - MARK DISTRIBUTION (Total: 3 marks)            │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. JSON Syntax Explanation                     │ 1.5 marks  │
│    - Definition of JSON                        │            │
│    - Syntax rules (name/value pairs, braces)   │            │
│    - Data type support                         │            │
│                                                │            │
│ 2. Comprehensive JSON Example                  │ 1.5 marks  │
│    - Complete example with nested structure    │            │
│    - Demonstrates all data types               │            │
│    - Shows objects, arrays, primitives         │            │
│    - Practical use case (student record)       │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Explanation + Example (Section 1.2, Pattern 2)

Question 10 (3 marks) — Describe the schema of a document implemented in JSON with suitable examples.

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, and constraints for JSON data.

JSON Schema Components:

  • $schema: Specifies JSON Schema version
  • title: Description of the schema
  • type: Data type (object, array, string, number, boolean, null)
  • properties: Defines object properties and their types
  • required: Lists mandatory fields

Example - Student Record Schema:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "title": "Student",
    "type": "object",
    "properties": {
        "id": {
            "type": "integer",
            "description": "Student ID"
        },
        "name": {
            "type": "string",
            "minLength": 3,
            "maxLength": 50
        },
        "email": {
            "type": "string",
            "format": "email"
        },
        "age": {
            "type": "integer",
            "minimum": 18,
            "maximum": 100
        },
        "courses": {
            "type": "array",
            "items": {
                "type": "string"
            }
        }
    },
    "required": ["id", "name", "email"]
}

Benefits:

  • Validates JSON data structure
  • Documents expected data format
  • Ensures data consistency
  • Enables auto-generation of documentation

Mark Distribution:

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 10 - MARK DISTRIBUTION (Total: 3 marks)           │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. JSON Schema Explanation                     │ 1.5 marks  │
│    - Definition of JSON schema                 │            │
│    - Schema components ($schema, title, etc.)  │            │
│    - Purpose of schema validation              │            │
│                                                │            │
│ 2. Detailed Schema Example                     │ 1.5 marks  │
│    - Complete student schema example           │            │
│    - Properties with data types                │            │
│    - Validation constraints (min, max, format) │            │
│    - Required fields specification             │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Explanation + Example (Section 1.2, Pattern 2)

PART B (Long Answer Questions)

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: (6 marks)

  • i. An image titled "flowers.jpg" with a height of 150 pixels and width of 250 pixels. If the image cannot be accessed, a message "No image available" should be displayed.
  • ii. A hyperlink to the URL "www.mysite.com/birds.jpg". The hyperlink should have the label "Click Here".
  • iii. An unordered list with values Tea, Coffee, 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>HTML Elements Demo</title>
</head>
<body>
    <h1>HTML Elements Implementation</h1>

    <!-- i. Image with alt text -->
    <h2>Image Element:</h2>
    <img src="flowers.jpg" alt="No image available" width="250" height="150">

    <!-- ii. Hyperlink -->
    <h2>Hyperlink:</h2>
    <a href="http://www.mysite.com/birds.jpg">Click Here</a>

    <!-- iii. Unordered List -->
    <h2>Beverages List:</h2>
    <ul>
        <li>Tea</li>
        <li>Coffee</li>
        <li>Milk</li>
    </ul>
</body>
</html>

b) Write the HTML code for obtaining the following table. (8 marks)

| Flower Show            |
|------------------------|
| **Flower Name** | **Colour** |
| Red Rose        | Red        |
| White Rose      | White      |
| Jasmine         |            |
| Sunflower       | Yellow     |

Answer:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flower Show Table</title>
</head>
<body>
    <table border="1" cellpadding="10" cellspacing="0" style="border-collapse: collapse; width: 320px; margin: 0 auto; text-align: center;">
        <thead>
            <tr>
                <th colspan="2" style="font-size: 20px;">Flower Show</th>
            </tr>
            <tr>
                <th>Flower Name</th>
                <th>Colour</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Red Rose</td>
                <td>Red</td>
            </tr>
            <tr>
                <td>White Rose</td>
                <td>White</td>
            </tr>
            <tr>
                <td>Jasmine</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>Sunflower</td>
                <td>Yellow</td>
            </tr>
        </tbody>
    </table>
</body>
</html>

Explanation:

  1. Table Header:

    • <thead> wraps two header rows so the title and column labels stay grouped.
    • colspan="2" on the first row spans the "Flower Show" text across both columns, matching the reference image.
    • Subsequent header cells define the "Flower Name" and "Colour" labels.
  2. Body Rows:

    • <tbody> contains each flower entry in its own <tr>.
    • The Jasmine row uses &nbsp; in the colour cell to keep the empty column visible without collapsing.
    • Remaining rows provide the requested flower/colour combinations.
  3. Presentation Details:

    • border="1", cellpadding="10", and cellspacing="0" replicate the bordered exam output.
    • Inline styles collapse borders, center text, and restrict width so the table resembles the prompt layout.

Mark Distribution (Part b):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 11b - MARK DISTRIBUTION (Total: 8 marks)          │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ Complete HTML Table Implementation             │ 8 marks    │
│    - DOCTYPE and HTML structure (1)            │            │
│    - Table tag with attributes (1)             │            │
│    - Header spanning two columns (colspan) (1)│            │
│    - Table header row with <th> (1)            │            │
│    - Data rows with correct content (2)        │            │
│    - Matching layout (border collapse, blank cell) (2)│     │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Complete Programming Solution (Section 3.2, Pattern 3)

Overall Question 11 Total: 14 marks (6 + 8)


Question 12 (14 marks)

a) Explain list tags with example. (6 marks)

Answer:

Definition:

HTML provides three types of list tags to organize and display information in a structured format: ordered lists, unordered lists, and description lists.

Types of Lists:

1. Unordered List (<ul>):

Creates a bulleted list where order doesn't matter. Each item is marked with a bullet point.

<h3>Shopping List</h3>
<ul>
    <li>Milk</li>
    <li>Bread</li>
    <li>Eggs</li>
    <li>Butter</li>
</ul>

Output:

  • Milk
  • Bread
  • Eggs
  • Butter

List Style Types for <ul>:

<ul style="list-style-type: circle;">  <!-- Hollow circles -->
<ul style="list-style-type: square;">  <!-- Squares -->
<ul style="list-style-type: disc;">    <!-- Filled circles (default) -->

2. Ordered List (<ol>):

Creates a numbered list where sequence matters. Items are automatically numbered.

<h3>Recipe Steps</h3>
<ol>
    <li>Preheat oven to 350°F</li>
    <li>Mix dry ingredients</li>
    <li>Add wet ingredients</li>
    <li>Bake for 30 minutes</li>
</ol>

Output:

  1. Preheat oven to 350°F
  2. Mix dry ingredients
  3. Add wet ingredients
  4. Bake for 30 minutes

List Style Types for <ol>:

<ol type="1">  <!-- Numbers (default): 1, 2, 3 -->
<ol type="A">  <!-- Uppercase letters: A, B, C -->
<ol type="a">  <!-- Lowercase letters: a, b, c -->
<ol type="I">  <!-- Roman numerals uppercase: I, II, III -->
<ol type="i">  <!-- Roman numerals lowercase: i, ii, iii -->
<ol start="5"> <!-- Start numbering from 5 -->

3. Description List (<dl>):

Creates a list of terms with their descriptions. Used for glossaries or key-value pairs.

<h3>Web Technologies</h3>
<dl>
    <dt>HTML</dt>
    <dd>HyperText Markup Language - structures web content</dd>

    <dt>CSS</dt>
    <dd>Cascading Style Sheets - styles web pages</dd>

    <dt>JavaScript</dt>
    <dd>Programming language for web interactivity</dd>
</dl>

Elements:

  • <dl>: Description list container
  • <dt>: Description term (the term being defined)
  • <dd>: Description definition (the description of the term)

4. Nested Lists:

Lists can be nested inside each other for hierarchical structures.

<h3>Course Structure</h3>
<ul>
    <li>Frontend Development
        <ul>
            <li>HTML</li>
            <li>CSS</li>
            <li>JavaScript</li>
        </ul>
    </li>
    <li>Backend Development
        <ol>
            <li>PHP</li>
            <li>MySQL</li>
            <li>Laravel</li>
        </ol>
    </li>
</ul>

Key Characteristics:

  • Unordered lists use bullets (for items without specific order)
  • Ordered lists use numbers/letters (for sequential items)
  • Description lists pair terms with definitions
  • Lists can be nested to create sub-levels
  • All lists use <li> tags for items (except description lists)

Mark Distribution (Part a):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 12a - MARK DISTRIBUTION (Total: 6 marks)          │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Unordered List (<ul>)                       │ 2 marks    │
│    - Definition and purpose                    │            │
│    - Example with code and output              │            │
│    - List style types                          │            │
│                                                │            │
│ 2. Ordered List (<ol>)                         │ 2 marks    │
│    - Definition and purpose                    │            │
│    - Example with code and output              │            │
│    - List style types (1, A, a, I, i)          │            │
│                                                │            │
│ 3. Description List & Nested Lists             │ 2 marks    │
│    - Description list (<dl>, <dt>, <dd>)       │            │
│    - Nested list example                       │            │
│    - Key characteristics summary               │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Three Equal Components (Section 2.2, Pattern 2)

b) Write the HTML code for obtaining the following registration form, where the course field contains the options BCA, BBA, B.Tech, MBA, MCA, M.Tech. (8 marks)

Answer:

Implementation:

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

    <form method="post" action="register.php">
        <!-- Name Fields -->
        <label for="firstname">Firstname:</label>
        <input type="text" id="firstname" name="firstname" required>
        <br><br>

        <label for="middlename">Middlename:</label>
        <input type="text" id="middlename" name="middlename">
        <br><br>

        <label for="lastname">Lastname:</label>
        <input type="text" id="lastname" name="lastname" required>
        <br><br>

        <!-- Course Dropdown -->
        <label for="course">Course:</label>
        <select id="course" name="course" required>
            <option value="">Course</option>
            <option value="BCA">BCA</option>
            <option value="BBA">BBA</option>
            <option value="B.Tech">B.Tech</option>
            <option value="MBA">MBA</option>
            <option value="MCA">MCA</option>
            <option value="M.Tech">M.Tech</option>
        </select>
        <br><br>

        <!-- Gender Radio Buttons -->
        <label>Gender:</label><br>
        <input type="radio" id="male" name="gender" value="Male" required>
        <label for="male">Male</label><br>

        <input type="radio" id="female" name="gender" value="Female">
        <label for="female">Female</label><br>

        <input type="radio" id="other" name="gender" value="Other">
        <label for="other">Other</label>
        <br><br>

        <!-- Phone Number -->
        <label for="phone">Phone:</label>
        <input type="text" id="countrycode" name="countrycode" value="+91" size="3">
        <input type="tel" id="phone" name="phone" pattern="[0-9]{10}" required>
        <br><br>

        <!-- Address Textarea -->
        <label for="address">Address:</label><br>
        <textarea id="address" name="address" rows="5" cols="50" required></textarea>
        <br><br>

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

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

        <!-- Confirm Password -->
        <label for="repassword">Re-type password:</label>
        <input type="password" id="repassword" name="repassword" required>
        <br><br>

        <!-- Submit Button -->
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Explanation:

Form Elements Used:

  1. Text Input Fields:

    • <input type="text">: For firstname, middlename, lastname
    • name attribute: Identifies field data when submitted
    • id attribute: Links label to input field
    • required attribute: Makes field mandatory
  2. Select Dropdown:

    • <select>: Creates dropdown menu for course selection
    • <option>: Each course option (BCA, BBA, B.Tech, MBA, MCA, M.Tech)
    • First option with empty value acts as placeholder
  3. Radio Buttons:

    • <input type="radio">: For gender selection (Male, Female, Other)
    • Same name attribute groups radio buttons (only one can be selected)
    • Different value attributes for each option
  4. Phone Number:

    • Country code field with size="3" and default value "+91"
    • <input type="tel">: For telephone number input
    • pattern="[0-9]{10}": Validates 10-digit phone number
  5. Textarea:

    • <textarea>: Multi-line input for address
    • rows="5" and cols="50": Sets dimensions
  6. Email Input:

    • <input type="email">: Validates email format automatically
    • Browser provides built-in validation
  7. Password Fields:

    • <input type="password">: Masks password input
    • Separate fields for password and confirmation
  8. Submit Button:

    • <input type="submit">: Submits form data to server
    • value attribute sets button text

Key Features:

  • Complete form with all required fields matching the specification
  • Proper use of HTML5 input types for validation
  • Labels linked to inputs using for and id attributes
  • Form method="post" for secure data submission
  • required attributes ensure mandatory fields are filled
  • Pattern validation for phone number format

Mark Distribution (Part b):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 12b - MARK DISTRIBUTION (Total: 8 marks)          │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ Complete HTML Registration Form                │ 8 marks    │
│    - HTML structure and form tag (1)           │            │
│    - Text inputs (firstname, middlename,       │            │
│      lastname) with labels (1)                 │            │
│    - Course dropdown with 6 options (1)        │            │
│    - Gender radio buttons (Male/Female/Other)  │            │
│      (1)                                       │            │
│    - Phone field with country code (1)         │            │
│    - Address textarea (1)                      │            │
│    - Email and password fields (1)             │            │
│    - Submit button and validation (1)          │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Complete Programming Solution (Section 3.2, Pattern 3)

Overall Question 12 Total: 14 marks (6 + 8)


Module II — Module II
Question 13 (14 marks)

a) Explain different levels of CSS Style Sheets with suitable example. (6 marks)

Answer:

Definition:

CSS (Cascading Style Sheets) can be applied to HTML documents in three different ways, each with its own use case and level of specificity. These levels determine the scope and priority of styling rules.

Three Levels of CSS:

1. Inline CSS

Applied directly to HTML elements using the style attribute. Has the highest priority and affects only the specific element.

Characteristics:

  • Applied directly within HTML tags
  • Highest specificity (overrides other styles)
  • Not reusable
  • Difficult to maintain for large projects

Example:

<!DOCTYPE html>
<html>
<head>
    <title>Inline CSS Example</title>
</head>
<body>
    <h1 style="color: blue; text-align: center; font-size: 32px;">Welcome</h1>
    <p style="color: red; font-family: Arial;">This paragraph uses inline CSS.</p>
    <div style="background-color: yellow; padding: 20px; border: 2px solid black;">
        Styled division using inline CSS
    </div>
</body>
</html>

2. Internal CSS (Embedded CSS)

Defined within the <style> tag in the <head> section of HTML document. Applies to the entire page.

Characteristics:

  • Defined in <style> tag within <head> section
  • Applies to entire HTML document
  • Better than inline for single-page styling
  • Medium specificity

Example:

<!DOCTYPE html>
<html>
<head>
    <title>Internal CSS Example</title>
    <style>
        body {
            background-color: #f0f0f0;
            font-family: 'Georgia', serif;
        }

        h1 {
            color: navy;
            text-align: center;
            text-decoration: underline;
        }

        p {
            color: green;
            font-size: 18px;
            line-height: 1.6;
        }

        .highlight {
            background-color: yellow;
            padding: 10px;
        }

        #special {
            border: 3px dashed red;
        }
    </style>
</head>
<body>
    <h1>Internal CSS Demo</h1>
    <p>This paragraph is styled using internal CSS.</p>
    <p class="highlight">This has a highlighted background.</p>
    <div id="special">This div has a special border.</div>
</body>
</html>

3. External CSS

Defined in a separate .css file and linked to HTML documents. Most efficient for multiple pages.

Characteristics:

  • Separate CSS file (e.g., style.css)
  • Linked using <link> tag in <head>
  • Can be used across multiple HTML pages
  • Best for large websites
  • Lowest specificity (can be overridden by internal/inline)
  • Enables caching for better performance

Example:

style.css (External CSS File):

/* Global styles */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: Arial, sans-serif;
    background-color: #ffffff;
    color: #333333;
}

header {
    background-color: #4CAF50;
    color: white;
    padding: 20px;
    text-align: center;
}

nav ul {
    list-style-type: none;
    background-color: #333;
}

nav ul li {
    display: inline;
    padding: 15px;
}

nav ul li a {
    color: white;
    text-decoration: none;
}

.container {
    width: 80%;
    margin: 20px auto;
}

index.html (Linking External CSS):

<!DOCTYPE html>
<html>
<head>
    <title>External CSS Example</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <header>
        <h1>Website Title</h1>
    </header>
    <nav>
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </nav>
    <div class="container">
        <p>Content styled using external CSS.</p>
    </div>
</body>
</html>

Comparison and Priority:

Aspect Inline CSS Internal CSS External CSS
Location Within HTML tag <style> in <head> Separate .css file
Scope Single element Single page Multiple pages
Priority Highest Medium Lowest
Reusability None Limited (one page) High (multiple pages)
Maintenance Difficult Moderate Easy
Best Use Quick single changes Single-page sites Large websites

Cascading Order (Priority):

  1. Inline CSS (highest priority)
  2. Internal CSS
  3. External CSS
  4. Browser default (lowest priority)

Note: !important declaration can override this natural cascading order.

Mark Distribution (Part a):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 13a - MARK DISTRIBUTION (Total: 6 marks)          │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Inline CSS                                  │ 2 marks    │
│    - Definition and characteristics            │            │
│    - Complete example with HTML code           │            │
│                                                │            │
│ 2. Internal CSS (Embedded)                     │ 2 marks    │
│    - Definition and characteristics            │            │
│    - Complete example with <style> tag         │            │
│                                                │            │
│ 3. External CSS                                │ 2 marks    │
│    - Definition and characteristics            │            │
│    - Example with separate .css file           │            │
│    - Comparison table and priority order       │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Three Equal Components (Section 2.2, Pattern 2)

b) Write JavaScript program to find factorial of a number, use prompt dialog box to get the input from user. (8 marks)

Answer:

Approach:

Factorial of a number n (denoted as n!) is the product of all positive integers from 1 to n. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. We'll use a prompt dialog to get user input and calculate the factorial using a loop.

Implementation:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Factorial Calculator</title>
</head>
<body>
    <h1>Factorial Calculator</h1>
    <button onclick="calculateFactorial()">Calculate Factorial</button>
    <div id="result"></div>

    <script>
        function calculateFactorial() {
            // Get input from user using prompt dialog
            let input = prompt("Enter a positive integer to find its factorial:");

            // Convert input to number
            let num = parseInt(input);

            // Validate input
            if (input === null || input === "") {
                alert("No input provided!");
                return;
            }

            if (isNaN(num)) {
                alert("Please enter a valid number!");
                return;
            }

            if (num < 0) {
                alert("Factorial is not defined for negative numbers!");
                return;
            }

            // Calculate factorial
            let factorial = 1;
            let steps = num + "! = ";

            if (num === 0 || num === 1) {
                factorial = 1;
                steps = num + "! = 1";
            } else {
                for (let i = num; i >= 1; i--) {
                    factorial *= i;
                    if (i > 1) {
                        steps += i + " × ";
                    } else {
                        steps += i + " = " + factorial;
                    }
                }
            }

            // Display result
            let resultDiv = document.getElementById("result");
            resultDiv.innerHTML = `
                <h2>Result:</h2>
                <p><strong>Number:</strong> ${num}</p>
                <p><strong>Calculation:</strong> ${steps}</p>
                <p><strong>Factorial:</strong> ${num}! = ${factorial}</p>
            `;
            resultDiv.style.backgroundColor = "#e8f5e9";
            resultDiv.style.padding = "20px";
            resultDiv.style.borderRadius = "5px";
            resultDiv.style.marginTop = "20px";
        }
    </script>
</body>
</html>

Alternative Method Using Recursion:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Factorial Calculator - Recursive</title>
</head>
<body>
    <h1>Factorial Calculator (Recursive Method)</h1>
    <button onclick="findFactorial()">Calculate Factorial</button>
    <p id="output"></p>

    <script>
        // Recursive function to calculate factorial
        function factorial(n) {
            if (n === 0 || n === 1) {
                return 1;
            } else {
                return n * factorial(n - 1);
            }
        }

        function findFactorial() {
            // Get input from prompt
            let num = prompt("Enter a number to find factorial:");

            // Convert to integer
            num = parseInt(num);

            // Input validation
            if (isNaN(num)) {
                alert("Invalid input! Please enter a number.");
                return;
            }

            if (num < 0) {
                alert("Factorial is not defined for negative numbers.");
                return;
            }

            // Calculate factorial
            let result = factorial(num);

            // Display result
            document.getElementById("output").innerHTML =
                `<strong>Factorial of ${num} is: ${result}</strong><br>` +
                `${num}! = ${result}`;
        }
    </script>
</body>
</html>

Explanation:

Iterative Method:

  1. Input Handling:

    • prompt() displays dialog box for user input
    • parseInt() converts string input to integer
    • Validation checks for null, empty, NaN, and negative values
  2. Factorial Calculation:

    • Initialize factorial = 1
    • Loop from num down to 1
    • Multiply each number: factorial *= i
    • Build step-by-step calculation string for display
  3. Special Cases:

    • 0! = 1 (by definition)
    • 1! = 1
    • Negative numbers: undefined (show error)
  4. Output Display:

    • Uses innerHTML to display formatted result
    • Shows calculation steps and final answer
    • Applies styling for better presentation

Recursive Method:

  • Base case: if n = 0 or n = 1, return 1
  • Recursive case: return n × factorial(n-1)
  • More elegant but less efficient for large numbers

Test Cases:

Input Output Calculation
5 120 5! = 5 × 4 × 3 × 2 × 1 = 120
0 1 0! = 1 (by definition)
1 1 1! = 1
10 3628800 10! = 3628800
-5 Error Undefined for negatives

Key Features:

  • User-friendly prompt dialog for input
  • Comprehensive input validation
  • Clear step-by-step calculation display
  • Handles edge cases (0, 1, negative numbers)
  • Both iterative and recursive implementations provided

Mark Distribution (Part b):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 13b - MARK DISTRIBUTION (Total: 8 marks)          │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ Complete JavaScript Factorial Program          │ 8 marks    │
│    - HTML structure with button (1)            │            │
│    - prompt() dialog for user input (1)        │            │
│    - Input validation (number check, negative  │            │
│      check) (2)                                │            │
│    - Factorial calculation logic (for loop or  │            │
│      recursion) (3)                            │            │
│    - Result display with formatting (1)        │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Complete Programming Solution (Section 3.2, Pattern 3)

Overall Question 13 Total: 14 marks (6 + 8)


Question 14 (14 marks)

a) Write CSS and the corresponding HTML code for the following: (8 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.jpg" as the background image of the page and set 3% margin for the page.
  • iv. Set dotted border for the document.

Answer:

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 Demo</title>
    <style>
        /* i. Link hover and active states with yellow background */
        a:hover {
            background-color: yellow;
        }

        a:active {
            background-color: yellow;
        }

        /* Optional: Normal link styling for visibility */
        a {
            text-decoration: none;
            color: blue;
            padding: 5px 10px;
            display: inline-block;
        }

        a:visited {
            color: purple;
        }

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

        /* iii. Body with background image and 3% margin */
        body {
            background-image: url('boat.jpg');
            background-repeat: no-repeat;
            background-size: cover;
            background-attachment: fixed;
            background-position: center;
            margin: 3%;
        }

        /* iv. Dotted border for the entire document */
        body {
            border: 3px dotted black;
            padding: 20px;
        }

        /* Additional styling for content visibility */
        .content {
            background-color: rgba(255, 255, 255, 0.9);
            padding: 20px;
            border-radius: 5px;
        }

        h1 {
            color: #333;
            text-align: center;
        }

        p {
            line-height: 1.6;
            color: #555;
        }
    </style>
</head>
<body>
    <div class="content">
        <h1>CSS Styling Demonstration</h1>

        <h2>Link Hover and Active States</h2>
        <p>Hover over or click these links to see yellow background:</p>
        <p>
            <a href="#home">Home</a>
            <a href="#about">About</a>
            <a href="#services">Services</a>
            <a href="#contact">Contact</a>
        </p>

        <h2>Ordered List with Lowercase Alphabet</h2>
        <ol>
            <li>First item (displayed as 'a')</li>
            <li>Second item (displayed as 'b')</li>
            <li>Third item (displayed as 'c')</li>
            <li>Fourth item (displayed as 'd')</li>
            <li>Fifth item (displayed as 'e')</li>
        </ol>

        <h2>Page Features</h2>
        <ul>
            <li>Background image: boat.jpg</li>
            <li>Page margin: 3%</li>
            <li>Document border: Dotted black border</li>
            <li>Link hover effect: Yellow background</li>
        </ul>

        <h2>Sample Content</h2>
        <p>
            This page demonstrates various CSS styling techniques including
            pseudo-classes for links, list styling, background images, margins,
            and borders. The background image (boat.jpg) covers the entire page,
            and the content is contained within a semi-transparent white box
            for better readability.
        </p>
    </div>
</body>
</html>

Detailed Explanation:

i. Link Hover and Active States:

a:hover {
    background-color: yellow;
}

a:active {
    background-color: yellow;
}
  • :hover pseudo-class: Applies styling when mouse hovers over the link
  • :active pseudo-class: Applies styling when link is being clicked
  • Both set background-color to yellow as required
  • Additional link states can include :link (unvisited) and :visited

ii. Ordered List Lowercase Alphabet:

ol {
    list-style-type: lower-alpha;
}
  • list-style-type: lower-alpha; displays items as a, b, c, d, e...
  • Other options include:
    • lower-alpha: a, b, c (as required)
    • upper-alpha: A, B, C
    • lower-roman: i, ii, iii
    • upper-roman: I, II, III
    • decimal: 1, 2, 3 (default)

iii. Background Image and Margin:

body {
    background-image: url('boat.jpg');
    background-repeat: no-repeat;
    background-size: cover;
    background-attachment: fixed;
    background-position: center;
    margin: 3%;
}
  • background-image: url('boat.jpg'): Sets boat.jpg as background
  • background-size: cover: Makes image cover entire viewport
  • background-attachment: fixed: Keeps background fixed during scrolling
  • background-position: center: Centers the image
  • margin: 3%: Sets 3% margin on all four sides of the page

iv. Dotted Border:

body {
    border: 3px dotted black;
    padding: 20px;
}
  • border: 3px dotted black: Creates dotted border around document
    • 3px: Border width
    • dotted: Border style (creates dots)
    • black: Border color
  • padding: 20px: Adds space between border and content

Key CSS Properties Demonstrated:

Property Value Purpose
background-color yellow Link hover/active background
list-style-type lower-alpha Lowercase alphabet list markers
background-image url('boat.jpg') Page background image
margin 3% Space outside document border
border 3px dotted black Dotted border around page

Output Description:

  • Webpage with boat.jpg as full-page background
  • 3% margin creating space around the page
  • Dotted black border framing the content
  • Links that turn yellow when hovered or clicked
  • Ordered list with lowercase letters (a, b, c, etc.)

Mark Distribution (Part a):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 14a - MARK DISTRIBUTION (Total: 8 marks)          │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ Complete CSS and HTML Implementation           │ 8 marks    │
│    - Link hover and active states CSS (2)      │            │
│    - Ordered list lowercase alphabet style (2) │            │
│    - Background image with 3% margin (2)       │            │
│    - Dotted border for document (2)            │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Four Equal Sub-Parts (Section 3.2, Pattern 4)

b) Explain various types of control statements in JavaScript with example. (6 marks)

Answer:

Definition:

Control statements in JavaScript are used to control the flow of program execution based on certain conditions or to repeat a block of code multiple times. They determine which code blocks should be executed and in what order.

Types of Control Statements:

1. Conditional Statements

Make decisions based on conditions and execute different code blocks accordingly.

a) if Statement:

Executes a block of code if a condition is true.

let age = 18;

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

b) if-else Statement:

Executes one block if condition is true, another if false.

let temperature = 25;

if (temperature > 30) {
    console.log("It's hot outside!");
} else {
    console.log("The weather is pleasant.");
}
// Output: The weather is pleasant.

c) if-else if-else Ladder:

Tests multiple conditions sequentially.

let marks = 85;

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

d) switch Statement:

Selects one of many code blocks to execute based on a value.

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;
    case 6:
        dayName = "Saturday";
        break;
    case 7:
        dayName = "Sunday";
        break;
    default:
        dayName = "Invalid day";
}

console.log("Today is " + dayName);
// Output: Today is Wednesday

2. Looping Statements

Repeat a block of code multiple times.

a) for Loop:

Repeats a block for a specified number of times.

// Print numbers 1 to 5
for (let i = 1; i <= 5; i++) {
    console.log("Number: " + i);
}
// Output: Number: 1, Number: 2, Number: 3, Number: 4, Number: 5

// Print even numbers from 2 to 10
for (let i = 2; i <= 10; i += 2) {
    console.log(i);
}
// Output: 2, 4, 6, 8, 10

b) while Loop:

Repeats as long as a condition is true.

let count = 1;

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

// Example: Sum of numbers
let sum = 0;
let n = 1;
while (n <= 10) {
    sum += n;
    n++;
}
console.log("Sum of 1 to 10: " + sum);
// Output: Sum of 1 to 10: 55

c) do-while Loop:

Executes at least once, then repeats while condition is true.

let num = 1;

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

// Executes at least once even if condition is false
let x = 10;
do {
    console.log("This will print once: " + x);
    x++;
} while (x < 5);
// Output: This will print once: 10

3. Jump Statements

Transfer control to another part of the program.

a) break Statement:

Exits from a loop or switch statement.

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

// Find first even number
for (let i = 1; i <= 10; i++) {
    if (i % 2 === 0) {
        console.log("First even number: " + i);
        break;
    }
}
// Output: First even number: 2

b) continue Statement:

Skips the current iteration and continues with the next.

// Print only odd numbers from 1 to 10
for (let i = 1; i <= 10; i++) {
    if (i % 2 === 0) {
        continue;  // Skip even numbers
    }
    console.log(i);
}
// Output: 1, 3, 5, 7, 9

// Skip multiples of 3
for (let i = 1; i <= 15; i++) {
    if (i % 3 === 0) {
        continue;
    }
    console.log(i);
}
// Output: 1, 2, 4, 5, 7, 8, 10, 11, 13, 14

Summary Table:

Control Statement Type Purpose When to Use
if Conditional Execute code if condition is true Single condition check
if-else Conditional Choose between two alternatives Two possible outcomes
if-else if-else Conditional Choose from multiple conditions Multiple conditions
switch Conditional Select one case from many Multiple discrete values
for Loop Repeat known number of times Counter-based iteration
while Loop Repeat while condition is true Unknown iterations, pre-test
do-while Loop Execute at least once Unknown iterations, post-test
break Jump Exit loop/switch Terminate loop early
continue Jump Skip current iteration Skip specific iterations

Key Characteristics:

  • Conditional statements make decisions based on boolean conditions
  • Looping statements repeat code blocks efficiently
  • Jump statements provide fine control within loops
  • Proper use of control statements makes code efficient and readable
  • Avoid infinite loops by ensuring loop conditions eventually become false

Mark Distribution (Part b):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 14b - MARK DISTRIBUTION (Total: 6 marks)          │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Conditional Statements                      │ 2 marks    │
│    - if, if-else, if-else if-else, switch      │            │
│    - Examples for each                         │            │
│                                                │            │
│ 2. Looping Statements                          │ 2 marks    │
│    - for, while, do-while loops                │            │
│    - Examples for each                         │            │
│                                                │            │
│ 3. Jump Statements & Summary                   │ 2 marks    │
│    - break and continue statements             │            │
│    - Examples and summary table                │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Three Equal Components (Section 2.2, Pattern 2)

Overall Question 14 Total: 14 marks (8 + 6)


Module III — Module III
Question 15 (14 marks)

a) Write a PHP program to compute the sum of the positive integers up to 100 using do while loop. (6 marks)

Answer:

Approach:

We need to calculate the sum: 1 + 2 + 3 + ... + 100 using a do-while loop. The do-while loop executes at least once and continues as long as the condition is true.

Implementation:

<?php
// Program to compute sum of positive integers up to 100 using do-while loop

// Initialize variables
$sum = 0;      // Variable to store the sum
$number = 1;   // Starting number

// Display program title
echo "<h2>Sum of Positive Integers from 1 to 100</h2>";
echo "<h3>Using do-while Loop</h3>";

// do-while loop to calculate sum
do {
    $sum += $number;  // Add current number to sum
    $number++;        // Increment number
} while ($number <= 100);

// Display the result
echo "<p><strong>Sum of integers from 1 to 100: </strong>" . $sum . "</p>";

// Additional: Show calculation formula
echo "<p><strong>Formula: </strong>1 + 2 + 3 + ... + 100 = " . $sum . "</p>";

// Verification using formula: n(n+1)/2
$n = 100;
$formulaResult = ($n * ($n + 1)) / 2;
echo "<p><strong>Verification (using formula n(n+1)/2): </strong>" . $formulaResult . "</p>";
?>

Alternative Version with Step Display:

<?php
// Program to show step-by-step calculation

$sum = 0;
$number = 1;
$steps = "";  // String to store calculation steps

echo "<h2>Sum Calculator (1 to 100)</h2>";

do {
    $sum += $number;

    // Build step string (show first 10 and last 10 for brevity)
    if ($number <= 10 || $number > 90) {
        $steps .= $number;
        if ($number < 100) {
            $steps .= " + ";
        }
    } else if ($number == 11) {
        $steps .= " ... + ";
    }

    $number++;
} while ($number <= 100);

echo "<p><strong>Calculation: </strong>" . $steps . "</p>";
echo "<p><strong>Total Sum: </strong>" . $sum . "</p>";
?>

Explanation:

  1. Initialization:

    • $sum = 0: Stores the cumulative sum
    • $number = 1: Counter variable starting from 1
  2. do-while Loop:

    • Executes the loop body first, then checks condition
    • $sum += $number: Adds current number to the sum
    • $number++: Increments counter after each iteration
    • while ($number <= 100): Continues until number exceeds 100
  3. Loop Execution Flow:

    • Iteration 1: sum = 0 + 1 = 1, number becomes 2
    • Iteration 2: sum = 1 + 2 = 3, number becomes 3
    • Iteration 3: sum = 3 + 3 = 6, number becomes 4
    • ... continues until ...
    • Iteration 100: sum = 4950 + 100 = 5050, number becomes 101
    • Condition (101 <= 100) is false, loop terminates
  4. Mathematical Verification:

    • Formula: Sum = n(n+1)/2 where n = 100
    • Sum = 100 × 101 / 2 = 10100 / 2 = 5050

Test Case:

Description Value
Start Number 1
End Number 100
Number of Terms 100
Total Sum 5050

Key Points:

  • do-while loop executes at least once before checking condition
  • Loop continues while number ≤ 100
  • Final result: 1 + 2 + 3 + ... + 100 = 5050

Mark Distribution (Part a):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 15a - MARK DISTRIBUTION (Total: 6 marks)          │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ Complete PHP Program with do-while Loop        │ 6 marks    │
│    - Variable initialization (1)               │            │
│    - do-while loop structure (2)               │            │
│    - Sum calculation logic (2)                 │            │
│    - Output display and verification (1)       │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Complete Programming Solution (Section 2.2, Pattern 5)

b) List the different ways to create an array in PHP with an example. Explain any 4 functions that deals with PHP array. (8 marks)

Answer:

Part 1: Different Ways to Create Arrays in PHP

1. Using array() Function:

<?php
// Indexed array
$fruits = array("Apple", "Banana", "Orange");

// Associative array
$ages = array("John" => 25, "Mary" => 30, "Bob" => 22);

// Multidimensional array
$students = array(
    array("Alice", 20, "Computer Science"),
    array("Bob", 21, "Mathematics"),
    array("Charlie", 19, "Physics")
);
?>

2. Using Short Array Syntax [] (PHP 5.4+):

<?php
// Indexed array
$colors = ["Red", "Green", "Blue"];

// Associative array
$prices = ["Apple" => 50, "Banana" => 30, "Orange" => 40];

// Mixed array
$mixed = ["Text", 42, true, 3.14];
?>

3. Creating Empty Array and Adding Elements:

<?php
// Create empty array
$numbers = array();

// Add elements using index
$numbers[0] = 10;
$numbers[1] = 20;
$numbers[2] = 30;

// Add elements without specifying index (auto-increment)
$numbers[] = 40;
$numbers[] = 50;

print_r($numbers);
// Output: Array ( [0] => 10 [1] => 20 [2] => 30 [3] => 40 [4] => 50 )
?>

4. Using range() Function:

<?php
// Create array of numbers from 1 to 10
$range1 = range(1, 10);

// Create array with step value
$range2 = range(0, 100, 10);  // 0, 10, 20, ..., 100

// Create array of letters
$range3 = range('a', 'z');

print_r($range1);
// Output: Array ( [0] => 1 [1] => 2 ... [9] => 10 )
?>

5. Using array_fill() Function:

<?php
// Fill array with same value
$filled = array_fill(0, 5, "Hello");
// Output: Array ( [0] => Hello [1] => Hello [2] => Hello [3] => Hello [4] => Hello )

// Fill with number
$zeros = array_fill(0, 10, 0);
?>

Part 2: Four Important PHP Array Functions

Function 1: count() / sizeof()

Purpose: Returns the number of elements in an array.

<?php
$fruits = ["Apple", "Banana", "Orange", "Mango"];
$count = count($fruits);

echo "Number of fruits: " . $count;  // Output: 4

// Count multidimensional array
$matrix = array(
    array(1, 2, 3),
    array(4, 5, 6)
);
echo "Elements (not recursive): " . count($matrix);  // Output: 2
echo "Elements (recursive): " . count($matrix, COUNT_RECURSIVE);  // Output: 8
?>

Function 2: array_push() and array_pop()

Purpose: Add elements to the end or remove elements from the end of an array.

<?php
$stack = ["HTML", "CSS"];

// Add elements to end
array_push($stack, "JavaScript");
array_push($stack, "PHP", "MySQL");

print_r($stack);
// Output: Array ( [0] => HTML [1] => CSS [2] => JavaScript [3] => PHP [4] => MySQL )

// Remove and return last element
$removed = array_pop($stack);
echo "Removed: " . $removed;  // Output: MySQL

print_r($stack);
// Output: Array ( [0] => HTML [1] => CSS [2] => JavaScript [3] => PHP )
?>

Function 3: sort() and rsort()

Purpose: Sort arrays in ascending or descending order.

<?php
// Indexed array sorting
$numbers = [45, 12, 78, 23, 56];

// Sort in ascending order
sort($numbers);
print_r($numbers);
// Output: Array ( [0] => 12 [1] => 23 [2] => 45 [3] => 56 [4] => 78 )

// Sort in descending order
rsort($numbers);
print_r($numbers);
// Output: Array ( [0] => 78 [1] => 56 [2] => 45 [3] => 23 [4] => 12 )

// For associative arrays (maintains key-value association)
$ages = ["John" => 25, "Alice" => 20, "Bob" => 30];

asort($ages);  // Sort by value, maintain keys
print_r($ages);
// Output: Array ( [Alice] => 20 [John] => 25 [Bob] => 30 )

ksort($ages);  // Sort by key
print_r($ages);
// Output: Array ( [Alice] => 20 [Bob] => 30 [John] => 25 )
?>

Function 4: array_merge() and array_slice()

Purpose: Merge multiple arrays or extract a portion of an array.

<?php
// array_merge() - Combine arrays
$array1 = ["Red", "Green"];
$array2 = ["Blue", "Yellow"];
$array3 = ["Purple", "Orange"];

$merged = array_merge($array1, $array2, $array3);
print_r($merged);
// Output: Array ( [0] => Red [1] => Green [2] => Blue [3] => Yellow [4] => Purple [5] => Orange )

// Merge associative arrays
$defaults = ["color" => "blue", "size" => "medium"];
$user = ["color" => "red", "weight" => "heavy"];
$config = array_merge($defaults, $user);
print_r($config);
// Output: Array ( [color] => red [size] => medium [weight] => heavy )

// array_slice() - Extract portion of array
$fruits = ["Apple", "Banana", "Orange", "Mango", "Grape"];

$slice1 = array_slice($fruits, 2);     // From index 2 to end
print_r($slice1);
// Output: Array ( [0] => Orange [1] => Mango [2] => Grape )

$slice2 = array_slice($fruits, 1, 3);  // From index 1, take 3 elements
print_r($slice2);
// Output: Array ( [0] => Banana [1] => Orange [2] => Mango )

$slice3 = array_slice($fruits, -2);    // Last 2 elements
print_r($slice3);
// Output: Array ( [0] => Mango [1] => Grape )
?>

Summary of Array Functions:

Function Purpose Example Usage
count() Count array elements count($array)
array_push() Add element(s) to end array_push($arr, "value")
array_pop() Remove last element $last = array_pop($arr)
sort() Sort ascending sort($arr)
rsort() Sort descending rsort($arr)
asort() Sort by value (keep keys) asort($arr)
ksort() Sort by key ksort($arr)
array_merge() Combine arrays array_merge($arr1, $arr2)
array_slice() Extract portion array_slice($arr, 2, 3)

Additional Useful Functions:

  • in_array(): Check if value exists in array
  • array_search(): Search for value and return key
  • array_keys(): Get all keys from array
  • array_values(): Get all values from array
  • array_unique(): Remove duplicate values
  • array_reverse(): Reverse array order

Key Points:

  • PHP arrays are versatile and can store mixed data types
  • Arrays can be indexed (numeric keys) or associative (string keys)
  • Multidimensional arrays create complex data structures
  • PHP provides extensive built-in functions for array manipulation
  • Modern PHP (5.4+) supports short array syntax []

Mark Distribution (Part b):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 15b - MARK DISTRIBUTION (Total: 8 marks)          │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Ways to Create Arrays in PHP                │ 3 marks    │
│    - array() function                          │            │
│    - Short syntax []                           │            │
│    - Empty array with element addition         │            │
│    - range() and array_fill() functions        │            │
│                                                │            │
│ 2. Four PHP Array Functions                    │ 5 marks    │
│    - count()/sizeof() (1.25)                   │            │
│    - array_push()/array_pop() (1.25)           │            │
│    - sort()/rsort()/asort()/ksort() (1.25)     │            │
│    - array_merge()/array_slice() (1.25)        │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Two Major Components - Concept + Implementation (Section 2.2, Pattern 4)

Overall Question 15 Total: 14 marks (6 + 8)


Question 16 (14 marks)

a) Explain the loops used in PHP with example. (8 marks)

Answer:

Definition:

Loops in PHP are control structures that allow you to execute a block of code repeatedly based on a condition. PHP provides four main types of loops: for, while, do-while, and foreach.

1. for Loop

Executes a code block for a specified number of times. Best used when you know the exact number of iterations.

Syntax:

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

Examples:

<?php
// Example 1: Print numbers 1 to 10
echo "<h3>Example 1: Numbers 1 to 10</h3>";
for ($i = 1; $i <= 10; $i++) {
    echo $i . " ";
}
// Output: 1 2 3 4 5 6 7 8 9 10

// Example 2: Print even numbers from 0 to 20
echo "<h3>Example 2: Even Numbers</h3>";
for ($i = 0; $i <= 20; $i += 2) {
    echo $i . " ";
}
// Output: 0 2 4 6 8 10 12 14 16 18 20

// Example 3: Multiplication table
echo "<h3>Example 3: Multiplication Table of 5</h3>";
for ($i = 1; $i <= 10; $i++) {
    echo "5 × $i = " . (5 * $i) . "<br>";
}
// Output: 5 × 1 = 5, 5 × 2 = 10, ... 5 × 10 = 50

// Example 4: Countdown
echo "<h3>Example 4: Countdown</h3>";
for ($i = 10; $i >= 1; $i--) {
    echo $i . "... ";
}
echo "Blast off!";
// Output: 10... 9... 8... 7... 6... 5... 4... 3... 2... 1... Blast off!
?>

2. while Loop

Executes code block as long as the specified condition is true. Condition is checked before each iteration.

Syntax:

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

Examples:

<?php
// Example 1: Print numbers 1 to 5
echo "<h3>Example 1: while Loop</h3>";
$count = 1;
while ($count <= 5) {
    echo "Count: $count<br>";
    $count++;
}
// Output: Count: 1, Count: 2, Count: 3, Count: 4, Count: 5

// Example 2: Sum of numbers until reaching 50
echo "<h3>Example 2: Sum until 50</h3>";
$sum = 0;
$number = 1;
while ($sum < 50) {
    $sum += $number;
    $number++;
}
echo "Sum: $sum, Last number added: " . ($number - 1);
// Output: Sum: 55, Last number added: 10

// Example 3: Generate random numbers until getting 5
echo "<h3>Example 3: Random Numbers</h3>";
$target = 5;
$attempts = 0;
$random = 0;

while ($random != $target) {
    $random = rand(1, 10);
    $attempts++;
    echo "Attempt $attempts: $random<br>";
}
echo "Found $target in $attempts attempts!";
?>

3. do-while Loop

Similar to while loop, but executes the code block at least once before checking the condition. Condition is checked after each iteration.

Syntax:

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

Examples:

<?php
// Example 1: Basic do-while
echo "<h3>Example 1: do-while Loop</h3>";
$x = 1;
do {
    echo "Number: $x<br>";
    $x++;
} while ($x <= 5);
// Output: Number: 1, Number: 2, Number: 3, Number: 4, Number: 5

// Example 2: Executes at least once even if condition is false
echo "<h3>Example 2: Executes at least once</h3>";
$y = 10;
do {
    echo "This prints once even though condition is false: $y<br>";
    $y++;
} while ($y < 5);
// Output: This prints once even though condition is false: 10

// Example 3: Menu-driven program simulation
echo "<h3>Example 3: Menu Simulation</h3>";
$choice = 0;
$iteration = 1;

do {
    echo "Menu Iteration $iteration<br>";
    echo "1. Option One<br>";
    echo "2. Option Two<br>";
    echo "3. Exit<br>";

    // Simulate user choice
    $choice = ($iteration < 3) ? $iteration : 3;
    echo "Selected: $choice<br><br>";
    $iteration++;
} while ($choice != 3);
echo "Exited from menu";
?>

4. foreach Loop

Specifically designed for arrays. Iterates through each element in an array without needing to know the array size.

Syntax:

// For indexed arrays
foreach ($array as $value) {
    // code to be executed
}

// For associative arrays
foreach ($array as $key => $value) {
    // code to be executed
}

Examples:

<?php
// Example 1: Iterate through indexed array
echo "<h3>Example 1: Indexed Array</h3>";
$fruits = ["Apple", "Banana", "Orange", "Mango"];

foreach ($fruits as $fruit) {
    echo "$fruit<br>";
}
// Output: Apple, Banana, Orange, Mango

// Example 2: Iterate through associative array
echo "<h3>Example 2: Associative Array</h3>";
$ages = ["John" => 25, "Alice" => 30, "Bob" => 22];

foreach ($ages as $name => $age) {
    echo "$name is $age years old<br>";
}
// Output: John is 25 years old, Alice is 30 years old, Bob is 22 years old

// Example 3: Multidimensional array
echo "<h3>Example 3: Multidimensional Array</h3>";
$students = [
    ["name" => "Alice", "marks" => 85],
    ["name" => "Bob", "marks" => 78],
    ["name" => "Charlie", "marks" => 92]
];

foreach ($students as $student) {
    echo "Name: " . $student["name"] . ", Marks: " . $student["marks"] . "<br>";
}

// Example 4: Modify array elements (use reference &)
echo "<h3>Example 4: Modify Array Elements</h3>";
$numbers = [1, 2, 3, 4, 5];

foreach ($numbers as &$num) {
    $num = $num * 2;  // Double each value
}
unset($num);  // Important: break the reference

print_r($numbers);
// Output: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 )
?>

Comparison of Loops:

Loop Type When to Use Condition Check Minimum Executions
for Known number of iterations Before each iteration 0
while Unknown iterations, may not execute at all Before each iteration 0
do-while Unknown iterations, must execute at least once After each iteration 1
foreach Iterating through arrays Automatic 0 (if array empty)

Loop Control Statements:

<?php
// break - Exit loop completely
echo "<h3>break Example</h3>";
for ($i = 1; $i <= 10; $i++) {
    if ($i == 5) {
        break;  // Exit loop when i equals 5
    }
    echo $i . " ";
}
// Output: 1 2 3 4

// continue - Skip current iteration
echo "<h3>continue Example</h3>";
for ($i = 1; $i <= 10; $i++) {
    if ($i % 2 == 0) {
        continue;  // Skip even numbers
    }
    echo $i . " ";
}
// Output: 1 3 5 7 9
?>

Key Characteristics:

  • for loop: Best for counter-based iterations
  • while loop: Best when iteration count is unknown
  • do-while loop: Guarantees at least one execution
  • foreach loop: Simplest way to iterate through arrays
  • Use break to exit loops early
  • Use continue to skip current iteration
  • Avoid infinite loops by ensuring conditions eventually become false

Mark Distribution (Part a):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 16a - MARK DISTRIBUTION (Total: 8 marks)          │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ Complete PHP Loops Explanation                 │ 8 marks    │
│    - for loop with examples (2)                │            │
│    - while loop with examples (2)              │            │
│    - do-while loop with examples (2)           │            │
│    - foreach loop with examples (2)            │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Four Equal Components (Section 3.2, Pattern 4)

b) Write equivalent PHP statements corresponding to the following: (6 marks)

  • i. Declare an associative array named "ages" to store the key-value pairs ("Harry",21), ("Alice",20), ("Megha", 22), ("Bob", 19).
  • ii. Modify the value associated with the key "Megha" to 28.
  • iii. Sort the array according to values maintaining the key-value relationships and print the sorted key-value pairs.
  • iv. The entry identified by the key "Alice".

Answer:

Implementation:

<?php
echo "<h2>PHP Associative Array Operations</h2>";

// i. Declare an associative array named "ages"
$ages = array(
    "Harry" => 21,
    "Alice" => 20,
    "Megha" => 22,
    "Bob" => 19
);

echo "<h3>i. Original Array:</h3>";
echo "<pre>";
print_r($ages);
echo "</pre>";
// Output: Array ( [Harry] => 21 [Alice] => 20 [Megha] => 22 [Bob] => 19 )

// ii. Modify the value associated with the key "Megha" to 28
$ages["Megha"] = 28;

echo "<h3>ii. After Modifying Megha's Age to 28:</h3>";
echo "<pre>";
print_r($ages);
echo "</pre>";
// Output: Array ( [Harry] => 21 [Alice] => 20 [Megha] => 28 [Bob] => 19 )

// iii. Sort the array according to values maintaining key-value relationships
asort($ages);  // Sort by value in ascending order, maintain key association

echo "<h3>iii. After Sorting by Values (ascending):</h3>";
echo "<pre>";
print_r($ages);
echo "</pre>";
// Output: Array ( [Bob] => 19 [Alice] => 20 [Harry] => 21 [Megha] => 28 )

echo "<h4>Sorted Key-Value Pairs:</h4>";
echo "<table border='1' cellpadding='10'>";
echo "<tr><th>Name</th><th>Age</th></tr>";
foreach ($ages as $name => $age) {
    echo "<tr><td>$name</td><td>$age</td></tr>";
}
echo "</table>";

// iv. Access the entry identified by the key "Alice"
echo "<h3>iv. Entry for key 'Alice':</h3>";
if (isset($ages["Alice"])) {
    echo "Alice's age is: " . $ages["Alice"];
} else {
    echo "Alice not found in the array";
}
// Output: Alice's age is: 20
?>

Alternative Methods for Each Operation:

<?php
echo "<h2>Alternative Methods</h2>";

// i. Alternative ways to declare associative array
// Method 1: Using array() function
$ages1 = array("Harry" => 21, "Alice" => 20, "Megha" => 22, "Bob" => 19);

// Method 2: Using short array syntax [] (PHP 5.4+)
$ages2 = ["Harry" => 21, "Alice" => 20, "Megha" => 22, "Bob" => 19];

// Method 3: Creating empty and adding elements
$ages3 = array();
$ages3["Harry"] = 21;
$ages3["Alice"] = 20;
$ages3["Megha"] = 22;
$ages3["Bob"] = 19;

// ii. Different ways to modify values
$ages["Megha"] = 28;  // Direct assignment
// OR using array_replace()
// $ages = array_replace($ages, ["Megha" => 28]);

// iii. Different sorting options
// asort() - Sort by value ascending, maintain keys
asort($ages);
echo "<h3>asort() - Ascending by value:</h3>";
print_r($ages);

// arsort() - Sort by value descending, maintain keys
$ages_copy = $ages;
arsort($ages_copy);
echo "<h3>arsort() - Descending by value:</h3>";
print_r($ages_copy);

// ksort() - Sort by key ascending
$ages_copy2 = $ages;
ksort($ages_copy2);
echo "<h3>ksort() - Ascending by key:</h3>";
print_r($ages_copy2);

// iv. Different ways to access array elements
// Method 1: Direct access
$alice_age = $ages["Alice"];
echo "Method 1 - Direct access: $alice_age<br>";

// Method 2: Using isset() for safe access
if (isset($ages["Alice"])) {
    echo "Method 2 - Safe access: " . $ages["Alice"] . "<br>";
}

// Method 3: Using array_key_exists()
if (array_key_exists("Alice", $ages)) {
    echo "Method 3 - array_key_exists(): " . $ages["Alice"] . "<br>";
}

// Method 4: Using null coalescing operator (PHP 7+)
$alice_age = $ages["Alice"] ?? "Not found";
echo "Method 4 - Null coalescing: $alice_age<br>";
?>

Complete Example with All Operations:

<?php
echo "<h2>Complete Example - All Operations in Sequence</h2>";

// i. Declare associative array
$ages = [
    "Harry" => 21,
    "Alice" => 20,
    "Megha" => 22,
    "Bob" => 19
];

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

// ii. Modify Megha's age
$ages["Megha"] = 28;
echo "<br><strong>Step 2 - After Modifying Megha's age:</strong><br>";
foreach ($ages as $name => $age) {
    echo "$name: $age<br>";
}

// iii. Sort by values maintaining keys
asort($ages);
echo "<br><strong>Step 3 - After Sorting by Values:</strong><br>";
foreach ($ages as $name => $age) {
    echo "$name: $age<br>";
}

// iv. Access Alice's entry
echo "<br><strong>Step 4 - Accessing Alice's Entry:</strong><br>";
echo "Alice's age: " . $ages["Alice"] . "<br>";

// Additional useful operations
echo "<br><strong>Additional Information:</strong><br>";
echo "Total people: " . count($ages) . "<br>";
echo "All names: " . implode(", ", array_keys($ages)) . "<br>";
echo "All ages: " . implode(", ", array_values($ages)) . "<br>";
echo "Average age: " . (array_sum($ages) / count($ages)) . "<br>";
?>

Explanation:

i. Array Declaration:

  • Associative arrays use string keys instead of numeric indices
  • Syntax: $array = ["key1" => value1, "key2" => value2]
  • Keys are case-sensitive

ii. Modifying Values:

  • Access array element by key and assign new value: $ages["Megha"] = 28
  • If key doesn't exist, it will be created
  • Existing value is overwritten

iii. Sorting Associative Arrays:

  • asort(): Sort by value ascending, maintain key-value association
  • arsort(): Sort by value descending, maintain keys
  • ksort(): Sort by key ascending
  • krsort(): Sort by key descending
  • Regular sort() would lose keys (not suitable for associative arrays)

iv. Accessing Elements:

  • Direct access: $ages["Alice"]
  • Safe access with isset() to avoid undefined key warnings
  • array_key_exists() checks if key exists (even if value is null)

Output of the Complete Program:

Step 1 - Original Array:
Harry: 21
Alice: 20
Megha: 22
Bob: 19

Step 2 - After Modifying Megha's age:
Harry: 21
Alice: 20
Megha: 28
Bob: 19

Step 3 - After Sorting by Values:
Bob: 19
Alice: 20
Harry: 21
Megha: 28

Step 4 - Accessing Alice's Entry:
Alice's age: 20

Key Points:

  • Associative arrays provide meaningful key-based access
  • Values can be modified using direct assignment
  • asort() maintains key-value relationships while sorting
  • Always check if key exists before accessing to avoid errors
  • Use print_r() or var_dump() for debugging array contents

Mark Distribution (Part b):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 16b - MARK DISTRIBUTION (Total: 6 marks)          │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ Complete PHP Statements Implementation         │ 6 marks    │
│    - Declare associative array "ages" (1.5)    │            │
│    - Modify value for key "Megha" (1.5)        │            │
│    - Sort by values with asort() and print     │            │
│      (2)                                       │            │
│    - Access entry by key "Alice" (1)           │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Four Sub-Parts with Varying Complexity (Section 2.2, Pattern 3)

Overall Question 16 Total: 14 marks (8 + 6)


Module IV — Module IV
Question 17 (14 marks)

a) Design the HTML page which enters two numbers and embed the PHP code to display the sum, difference, product and quotient of these two numbers, when clicking the 'CALCULATE' button. (8 marks)

Answer:

Implementation:

<!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>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 50px auto;
            padding: 20px;
            background-color: #f4f4f4;
        }

        .container {
            background-color: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }

        h1 {
            color: #333;
            text-align: center;
        }

        .form-group {
            margin-bottom: 15px;
        }

        label {
            display: block;
            margin-bottom: 5px;
            color: #555;
            font-weight: bold;
        }

        input[type="number"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
            box-sizing: border-box;
        }

        button {
            width: 100%;
            padding: 12px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 18px;
            cursor: pointer;
            margin-top: 10px;
        }

        button:hover {
            background-color: #45a049;
        }

        .result-box {
            margin-top: 20px;
            padding: 20px;
            background-color: #e8f5e9;
            border-left: 4px solid #4CAF50;
            border-radius: 5px;
        }

        .result-box h2 {
            margin-top: 0;
            color: #2e7d32;
        }

        .result-item {
            padding: 8px 0;
            font-size: 16px;
            border-bottom: 1px solid #c8e6c9;
        }

        .result-item:last-child {
            border-bottom: none;
        }

        .error-box {
            margin-top: 20px;
            padding: 15px;
            background-color: #ffebee;
            border-left: 4px solid #f44336;
            border-radius: 5px;
            color: #c62828;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Number Calculator</h1>

        <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
            <div class="form-group">
                <label for="number1">First Number:</label>
                <input type="number" id="number1" name="number1" step="any" required
                       value="<?php echo isset($_POST['number1']) ? $_POST['number1'] : ''; ?>">
            </div>

            <div class="form-group">
                <label for="number2">Second Number:</label>
                <input type="number" id="number2" name="number2" step="any" required
                       value="<?php echo isset($_POST['number2']) ? $_POST['number2'] : ''; ?>">
            </div>

            <button type="submit" name="calculate">CALCULATE</button>
        </form>

        <?php
        // PHP code to process the form and calculate results
        if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['calculate'])) {
            // Get the input values
            $number1 = floatval($_POST['number1']);
            $number2 = floatval($_POST['number2']);

            // Perform calculations
            $sum = $number1 + $number2;
            $difference = $number1 - $number2;
            $product = $number1 * $number2;

            // Display results
            echo '<div class="result-box">';
            echo '<h2>Calculation Results</h2>';
            echo '<div class="result-item"><strong>First Number:</strong> ' . $number1 . '</div>';
            echo '<div class="result-item"><strong>Second Number:</strong> ' . $number2 . '</div>';
            echo '<div class="result-item"><strong>Sum:</strong> ' . $number1 . ' + ' . $number2 . ' = ' . $sum . '</div>';
            echo '<div class="result-item"><strong>Difference:</strong> ' . $number1 . ' - ' . $number2 . ' = ' . $difference . '</div>';
            echo '<div class="result-item"><strong>Product:</strong> ' . $number1 . ' × ' . $number2 . ' = ' . $product . '</div>';

            // Check for division by zero
            if ($number2 != 0) {
                $quotient = $number1 / $number2;
                echo '<div class="result-item"><strong>Quotient:</strong> ' . $number1 . ' ÷ ' . $number2 . ' = ' . number_format($quotient, 4) . '</div>';
            } else {
                echo '<div class="error-box"><strong>Error:</strong> Cannot divide by zero!</div>';
            }

            echo '</div>';
        }
        ?>
    </div>
</body>
</html>

Explanation:

HTML Structure:

  1. Form Elements:

    • Two <input type="number"> fields for entering numbers
    • step="any" allows decimal numbers
    • required attribute ensures fields are filled
    • Form uses POST method for data submission
    • Action points to same page ($_SERVER["PHP_SELF"])
  2. Button:

    • Submit button with name="calculate"
    • Triggers form submission and PHP processing

PHP Processing:

  1. Form Submission Check:

    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['calculate']))
    • Verifies POST request and button click
  2. Input Processing:

    • floatval() converts string input to float numbers
    • Handles both integers and decimals
  3. Calculations:

    • Sum: $sum = $number1 + $number2
    • Difference: $difference = $number1 - $number2
    • Product: $product = $number1 * $number2
    • Quotient: $quotient = $number1 / $number2 (with zero-check)
  4. Division by Zero Handling:

    • Checks if $number2 != 0 before division
    • Displays error message for division by zero
    • Prevents PHP fatal error
  5. Output Formatting:

    • number_format($quotient, 4) formats quotient to 4 decimal places
    • Results displayed in formatted HTML divs
    • Professional styling for better user experience

CSS Styling:

  • Clean, professional interface
  • Responsive layout centered on page
  • Green color scheme for results
  • Red error box for division by zero
  • Input fields with proper spacing and borders
  • Hover effects on button

Test Cases:

Input 1 Input 2 Sum Difference Product Quotient
10 5 15 5 50 2.0000
20 4 24 16 80 5.0000
7.5 2.5 10.0 5.0 18.75 3.0000
15 0 15 15 0 Error: Division by zero
-10 5 -5 -15 -50 -2.0000

Key Features:

  • Complete HTML5 document with proper DOCTYPE
  • Self-processing form (submits to same page)
  • Input validation using HTML5 required attribute
  • PHP type conversion with floatval()
  • Division by zero error handling
  • Professional internal CSS styling
  • User-friendly result display
  • Preserves input values after submission
  • Security: Uses htmlspecialchars() for form action

Mark Distribution (Part a):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 17a - MARK DISTRIBUTION (Total: 8 marks)          │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ Complete HTML + PHP Calculator                 │ 8 marks    │
│    - HTML form with two number inputs (2)      │            │
│    - CALCULATE button (1)                      │            │
│    - PHP processing logic (3)                  │            │
│      - Sum and difference calculation          │            │
│      - Product and quotient calculation        │            │
│      - Division by zero handling               │            │
│    - Result display formatting (2)             │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Complete Programming Solution (Section 3.2, Pattern 3)

b) What are the uses of cookies in web pages? Describe syntax for setting cookies in PHP. How can you access and delete the cookie using setcookie() function? (6 marks)

Answer:

Uses of Cookies in Web Pages:

Cookies are small text files stored on the client's browser by web servers. They enable stateful sessions in the stateless HTTP protocol.

Common Uses:

  1. User Authentication and Session Management:

    • Storing login tokens
    • Remembering user login status
    • Maintaining session across multiple pages
  2. Personalization:

    • Saving user preferences (theme, language, layout)
    • Storing shopping cart items
    • Remembering user choices
  3. Tracking and Analytics:

    • Tracking user behavior and navigation patterns
    • Collecting analytics data
    • Understanding user interactions
  4. Advertising:

    • Delivering targeted advertisements
    • Tracking ad campaign effectiveness
    • Cross-site tracking (third-party cookies)
  5. Form Data Persistence:

    • Remembering form inputs
    • Auto-filling repeated information
    • Saving incomplete form data

Setting Cookies in PHP:

Syntax:

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

Parameters:

Parameter Description Example
name Cookie name (required) "username"
value Cookie value "John"
expire Expiration time (Unix timestamp) time() + 3600 (1 hour)
path Server path where cookie is available "/" (entire domain)
domain Domain where cookie is available ".example.com"
secure Transmit only over HTTPS true or false
httponly Accessible only via HTTP (not JavaScript) true or false

Examples of Setting Cookies:

<?php
// Example 1: Simple cookie (expires when browser closes)
setcookie("user", "JohnDoe");

// Example 2: Cookie with 1 hour expiration
setcookie("username", "Alice", time() + 3600);

// Example 3: Cookie with 30 days expiration
setcookie("theme", "dark", time() + (86400 * 30)); // 86400 seconds = 1 day

// Example 4: Cookie available for entire domain
setcookie("language", "English", time() + 3600, "/");

// Example 5: Secure cookie (HTTPS only) with HttpOnly flag
setcookie("token", "abc123xyz", time() + 7200, "/", "", true, true);

// Example 6: Cookie for specific subdomain
setcookie("region", "US", time() + 3600, "/", ".mywebsite.com");

// Example 7: Multiple cookies
setcookie("first_name", "John", time() + 3600, "/");
setcookie("last_name", "Doe", time() + 3600, "/");
setcookie("email", "john@example.com", time() + 3600, "/");
?>

Important Notes for Setting Cookies:

  • MUST be called before any HTML output (including whitespace, echo, or print statements)
  • Cookies are sent with HTTP headers
  • Output before setcookie() causes "headers already sent" error

Correct vs Incorrect:

<?php
// ✅ CORRECT - setcookie before any output
setcookie("user", "John", time() + 3600);
?>
<!DOCTYPE html>
<html>
<body>
    <h1>Welcome</h1>
</body>
</html>

<?php
// ❌ INCORRECT - output before setcookie
?>
<!DOCTYPE html>
<html>
<?php
setcookie("user", "John", time() + 3600); // ERROR: Headers already sent
?>
<body>
    <h1>Welcome</h1>
</body>
</html>

Accessing Cookies:

Cookies are accessed using the $_COOKIE superglobal array.

<?php
// Example 1: Check if cookie exists and access it
if (isset($_COOKIE["username"])) {
    $username = $_COOKIE["username"];
    echo "Welcome back, " . $username;
} else {
    echo "Welcome, Guest!";
}

// Example 2: Safe access with default value
$theme = $_COOKIE["theme"] ?? "light"; // PHP 7+ null coalescing operator
echo "Current theme: " . $theme;

// Example 3: Accessing multiple cookies
if (isset($_COOKIE["first_name"]) && isset($_COOKIE["last_name"])) {
    echo "User: " . $_COOKIE["first_name"] . " " . $_COOKIE["last_name"];
}

// Example 4: Display all cookies
echo "<h3>All Cookies:</h3>";
foreach ($_COOKIE as $name => $value) {
    echo "$name: $value<br>";
}

// Example 5: Count total cookies
$cookieCount = count($_COOKIE);
echo "Total cookies: " . $cookieCount;
?>

Cookie Availability:

  • Cookies set on current page are NOT immediately available in $_COOKIE
  • They become available on the next page load or reload
  • Cookies are sent by the browser with each HTTP request

Deleting Cookies:

To delete a cookie, set its expiration time to a past date using setcookie().

Methods to Delete Cookies:

Method 1: Set expiration to past time (Recommended)

<?php
// Delete cookie by setting expiration to past
setcookie("username", "", time() - 3600); // 1 hour ago

// Alternative: Even further in the past
setcookie("username", "", time() - 86400); // 1 day ago

// Or use value 1 (January 1, 1970)
setcookie("username", "", 1);
?>

Method 2: Set expiration to current time - 1

<?php
// Delete by expiring immediately
setcookie("username", "", time() - 1, "/");
?>

Method 3: Match all original parameters

When deleting, provide the same path, domain, secure, and httponly parameters used when creating the cookie.

<?php
// Setting cookie with specific parameters
setcookie("token", "abc123", time() + 3600, "/admin", ".example.com", true, true);

// Deleting the same cookie - MUST match path and domain
setcookie("token", "", time() - 3600, "/admin", ".example.com", true, true);
?>

Complete Example - Set, Access, and Delete Cookies:

<?php
// page1.php - Setting cookies
setcookie("username", "Alice", time() + 3600, "/");
setcookie("user_id", "12345", time() + 3600, "/");
setcookie("login_time", date("Y-m-d H:i:s"), time() + 3600, "/");

echo "<h2>Cookies Set Successfully!</h2>";
echo "<a href='page2.php'>Go to Page 2 to view cookies</a>";
?>

<?php
// page2.php - Accessing cookies
?>
<!DOCTYPE html>
<html>
<head>
    <title>View Cookies</title>
</head>
<body>
    <h2>Cookie Information:</h2>
    <?php
    if (isset($_COOKIE["username"])) {
        echo "<p><strong>Username:</strong> " . $_COOKIE["username"] . "</p>";
        echo "<p><strong>User ID:</strong> " . $_COOKIE["user_id"] . "</p>";
        echo "<p><strong>Login Time:</strong> " . $_COOKIE["login_time"] . "</p>";
    } else {
        echo "<p>No cookies found!</p>";
    }
    ?>
    <a href='page3.php'>Delete Cookies</a>
</body>
</html>

<?php
// page3.php - Deleting cookies
setcookie("username", "", time() - 3600, "/");
setcookie("user_id", "", time() - 3600, "/");
setcookie("login_time", "", time() - 3600, "/");

echo "<h2>Cookies Deleted Successfully!</h2>";
echo "<a href='page2.php'>Go back to Page 2</a>";
?>

Important Points for Cookie Deletion:

  1. Path and Domain Must Match:

    • Use same path and domain parameters as when setting
    • Otherwise, cookie won't be deleted
  2. Set Empty Value:

    • Setting value to empty string "" is good practice
    • Some browsers require this
  3. Past Expiration Time:

    • Any time in the past works
    • Common: time() - 3600 (1 hour ago)
  4. Immediate Deletion:

    • Cookie deletion takes effect on next page load
    • Not immediate in current script

Summary Table:

Operation Function Example
Set Cookie setcookie() setcookie("name", "value", time()+3600, "/");
Access Cookie $_COOKIE[] $value = $_COOKIE["name"];
Check if Exists isset() if (isset($_COOKIE["name"])) {...}
Delete Cookie setcookie() with past time setcookie("name", "", time()-3600, "/");

Key Points:

  • Cookies store data on client side (browser)
  • Maximum size: ~4KB per cookie
  • Cookies are sent with every HTTP request to the domain
  • setcookie() must be called before any HTML output
  • Always validate and sanitize cookie data (user can modify)
  • Use HttpOnly flag to prevent JavaScript access (security)
  • Use Secure flag for HTTPS-only transmission
  • Delete cookies by setting expiration to past time with matching parameters

Mark Distribution (Part b):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 17b - MARK DISTRIBUTION (Total: 6 marks)          │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Uses of Cookies in Web Pages                │ 2 marks    │
│    - Authentication and session management     │            │
│    - Personalization and tracking              │            │
│                                                │            │
│ 2. setcookie() Syntax and Setting Cookies      │ 2 marks    │
│    - Function syntax with parameters           │            │
│    - Examples of setting cookies               │            │
│                                                │            │
│ 3. Accessing and Deleting Cookies              │ 2 marks    │
│    - Accessing with $_COOKIE superglobal       │            │
│    - Deleting by setting past expiration       │            │
│    - Complete code examples                    │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Three Equal Components (Section 2.2, Pattern 2)

Overall Question 17 Total: 14 marks (8 + 6)


Question 18 (14 marks)

a) What is a PHP session, explain how to start, modify and destroy session variables with example. (7 marks)

Answer:

Definition:

A PHP session is a way to store information about a user across multiple pages on a website. Unlike cookies (which are stored on the client side), session data is stored on the server, making it more secure. Sessions allow you to preserve user state and data as they navigate through different pages.

Key Characteristics of Sessions:

  1. Server-Side Storage: Session data is stored on the server, not in the browser
  2. Session ID: A unique identifier (session ID) is stored in a cookie or URL parameter
  3. Temporary: Session data exists until the session is destroyed or expires
  4. More Secure: Data cannot be directly accessed or modified by the user
  5. Larger Storage: Can store more data compared to cookies (typically limited by server configuration)

How Sessions Work:

  1. User visits website → session_start() is called
  2. Server creates unique session ID
  3. Session ID sent to browser (usually via cookie)
  4. Server stores session data associated with that ID
  5. On subsequent requests, browser sends session ID
  6. Server retrieves session data using the ID

1. Starting a Session:

Use session_start() function to initiate or resume a session. Must be called before any HTML output.

<?php
// Start session - MUST be at the beginning before any output
session_start();
?>
<!DOCTYPE html>
<html>
<head>
    <title>PHP Session Example</title>
</head>
<body>
    <h1>Session Started</h1>
    <p>Session ID: <?php echo session_id(); ?></p>
</body>
</html>

Important:

  • Call session_start() at the beginning of every page that needs session access
  • Must be called before any HTML, echo, or whitespace output
  • Automatically creates session if none exists, or resumes existing session

2. Setting (Creating/Modifying) Session Variables:

Store data in the $_SESSION superglobal array.

<?php
session_start();

// Example 1: Setting session variables
$_SESSION["username"] = "Alice";
$_SESSION["email"] = "alice@example.com";
$_SESSION["user_id"] = 12345;
$_SESSION["role"] = "admin";

echo "Session variables set successfully!";
?>

Complete Example - Login System:

<?php
// login.php - Setting session variables after successful login
session_start();

// Simulate login validation
$input_username = "alice";
$input_password = "password123";

// In real application, verify against database
if ($input_username == "alice" && $input_password == "password123") {
    // Set session variables upon successful login
    $_SESSION["logged_in"] = true;
    $_SESSION["username"] = $input_username;
    $_SESSION["user_id"] = 101;
    $_SESSION["login_time"] = date("Y-m-d H:i:s");
    $_SESSION["user_role"] = "administrator";

    echo "<h2>Login Successful!</h2>";
    echo "<p>Welcome, " . $_SESSION["username"] . "</p>";
    echo "<a href='dashboard.php'>Go to Dashboard</a>";
} else {
    echo "<h2>Login Failed!</h2>";
    echo "<p>Invalid credentials</p>";
}
?>

3. Accessing Session Variables:

Read session data using the $_SESSION array.

<?php
// dashboard.php - Accessing session variables
session_start();

// Check if user is logged in
if (isset($_SESSION["logged_in"]) && $_SESSION["logged_in"] === true) {
    echo "<h2>Welcome to Dashboard</h2>";
    echo "<p><strong>Username:</strong> " . $_SESSION["username"] . "</p>";
    echo "<p><strong>User ID:</strong> " . $_SESSION["user_id"] . "</p>";
    echo "<p><strong>Login Time:</strong> " . $_SESSION["login_time"] . "</p>";
    echo "<p><strong>Role:</strong> " . $_SESSION["user_role"] . "</p>";

    echo "<br><a href='logout.php'>Logout</a>";
} else {
    echo "<h2>Access Denied</h2>";
    echo "<p>Please <a href='login.php'>login</a> to continue.</p>";
}
?>

4. Modifying Session Variables:

Modify session variables by simply reassigning values.

<?php
session_start();

// Display current values
echo "<h3>Current Session Data:</h3>";
echo "Username: " . $_SESSION["username"] . "<br>";
echo "Email: " . $_SESSION["email"] . "<br>";
echo "Role: " . $_SESSION["role"] . "<br><br>";

// Modify session variables
$_SESSION["username"] = "Bob";  // Change username
$_SESSION["email"] = "bob@example.com";  // Update email
$_SESSION["last_update"] = date("Y-m-d H:i:s");  // Add new variable
$_SESSION["role"] = "moderator";  // Change role

// Display updated values
echo "<h3>Updated Session Data:</h3>";
echo "Username: " . $_SESSION["username"] . "<br>";
echo "Email: " . $_SESSION["email"] . "<br>";
echo "Role: " . $_SESSION["role"] . "<br>";
echo "Last Update: " . $_SESSION["last_update"] . "<br>";
?>

5. Destroying Session Variables:

There are several ways to remove session data:

Method 1: Remove specific session variable using unset()

<?php
session_start();

// Remove a specific session variable
unset($_SESSION["username"]);
unset($_SESSION["email"]);

echo "Specific session variables removed!";

// Other session variables still exist
if (isset($_SESSION["user_id"])) {
    echo "<br>User ID still exists: " . $_SESSION["user_id"];
}
?>

Method 2: Remove all session variables

<?php
session_start();

// Method 2a: Unset all session variables
$_SESSION = array();  // Clear the entire session array

echo "All session variables cleared!";
?>

Method 3: Destroy entire session (complete logout)

<?php
// logout.php - Complete session destruction
session_start();

// Step 1: Unset all session variables
$_SESSION = array();

// Step 2: Delete the session cookie if it exists
if (isset($_COOKIE[session_name()])) {
    setcookie(session_name(), '', time() - 3600, '/');
}

// Step 3: Destroy the session
session_destroy();

echo "<h2>Logout Successful</h2>";
echo "<p>All session data has been destroyed.</p>";
echo "<a href='login.php'>Login Again</a>";
?>

Proper Session Destruction (Recommended Approach):

<?php
session_start();

// Complete cleanup process
function destroySession() {
    // 1. Unset all session variables
    $_SESSION = [];

    // 2. If using cookies for session, delete the session cookie
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(
            session_name(),
            '',
            time() - 42000,
            $params["path"],
            $params["domain"],
            $params["secure"],
            $params["httponly"]
        );
    }

    // 3. Destroy the session data on server
    session_destroy();
}

// Call the function
destroySession();

echo "Session completely destroyed!";
?>

Complete Working Example - Session Management System:

<?php
// page1.php - Start and Set Session
session_start();
?>
<!DOCTYPE html>
<html>
<head>
    <title>Page 1 - Start Session</title>
</head>
<body>
    <h1>Page 1: Starting Session</h1>

    <?php
    // Set session variables
    $_SESSION["username"] = "JohnDoe";
    $_SESSION["email"] = "john@example.com";
    $_SESSION["points"] = 100;
    $_SESSION["level"] = 5;

    echo "<p>Session ID: " . session_id() . "</p>";
    echo "<p>Session variables created:</p>";
    echo "<ul>";
    echo "<li>Username: " . $_SESSION["username"] . "</li>";
    echo "<li>Email: " . $_SESSION["email"] . "</li>";
    echo "<li>Points: " . $_SESSION["points"] . "</li>";
    echo "<li>Level: " . $_SESSION["level"] . "</li>";
    echo "</ul>";
    ?>

    <a href="page2.php">Go to Page 2 (View Session)</a>
</body>
</html>

<?php
// page2.php - Access and Display Session
session_start();
?>
<!DOCTYPE html>
<html>
<head>
    <title>Page 2 - View Session</title>
</head>
<body>
    <h1>Page 2: Viewing Session Data</h1>

    <?php
    if (isset($_SESSION["username"])) {
        echo "<p>Session is active!</p>";
        echo "<p>Session ID: " . session_id() . "</p>";
        echo "<h3>Current Session Variables:</h3>";
        echo "<ul>";
        foreach ($_SESSION as $key => $value) {
            echo "<li><strong>$key:</strong> $value</li>";
        }
        echo "</ul>";
    } else {
        echo "<p>No active session found!</p>";
    }
    ?>

    <a href="page3.php">Go to Page 3 (Modify Session)</a>
</body>
</html>

<?php
// page3.php - Modify Session
session_start();
?>
<!DOCTYPE html>
<html>
<head>
    <title>Page 3 - Modify Session</title>
</head>
<body>
    <h1>Page 3: Modifying Session Data</h1>

    <?php
    // Display current values
    echo "<h3>Before Modification:</h3>";
    echo "<p>Username: " . $_SESSION["username"] . "</p>";
    echo "<p>Points: " . $_SESSION["points"] . "</p>";

    // Modify session variables
    $_SESSION["username"] = "JaneDoe";
    $_SESSION["points"] = 250;
    $_SESSION["last_modified"] = date("Y-m-d H:i:s");

    // Display updated values
    echo "<h3>After Modification:</h3>";
    echo "<p>Username: " . $_SESSION["username"] . "</p>";
    echo "<p>Points: " . $_SESSION["points"] . "</p>";
    echo "<p>Last Modified: " . $_SESSION["last_modified"] . "</p>";
    ?>

    <a href="page4.php">Go to Page 4 (Destroy Session)</a>
</body>
</html>

<?php
// page4.php - Destroy Session
session_start();
?>
<!DOCTYPE html>
<html>
<head>
    <title>Page 4 - Destroy Session</title>
</head>
<body>
    <h1>Page 4: Destroying Session</h1>

    <?php
    // Display session data before destruction
    echo "<h3>Session Data Before Destruction:</h3>";
    if (!empty($_SESSION)) {
        foreach ($_SESSION as $key => $value) {
            echo "<p><strong>$key:</strong> $value</p>";
        }
    }

    // Destroy the session
    $_SESSION = array();

    if (isset($_COOKIE[session_name()])) {
        setcookie(session_name(), '', time() - 3600, '/');
    }

    session_destroy();

    echo "<h3>Session Destroyed!</h3>";
    echo "<p>All session data has been removed.</p>";
    ?>

    <a href="page2.php">Go back to Page 2 (No session will be found)</a><br>
    <a href="page1.php">Start a new session</a>
</body>
</html>

Session Function Summary:

Function Purpose Example
session_start() Start or resume session session_start();
$_SESSION["key"] = value Set session variable $_SESSION["user"] = "Alice";
$_SESSION["key"] Access session variable echo $_SESSION["user"];
isset($_SESSION["key"]) Check if variable exists if (isset($_SESSION["user"]))
unset($_SESSION["key"]) Remove specific variable unset($_SESSION["user"]);
$_SESSION = array() Clear all variables $_SESSION = [];
session_destroy() Destroy entire session session_destroy();
session_id() Get session ID echo session_id();
session_name() Get session name echo session_name();

Key Points:

  • session_start() must be called before accessing session data
  • Session data persists across multiple pages until destroyed or expired
  • More secure than cookies (stored on server)
  • Ideal for storing sensitive information (login status, user data)
  • Sessions automatically expire after inactivity (default ~24 minutes)
  • Always destroy sessions properly during logout
  • Use sessions for authentication and authorization
  • Can store arrays and objects in session variables

Mark Distribution (Part a):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 18a - MARK DISTRIBUTION (Total: 7 marks)          │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. PHP Session Definition and Concepts          │ 2 marks    │
│    - What is a session                         │            │
│    - Key characteristics                       │            │
│                                                │            │
│ 2. Starting and Modifying Sessions             │ 2.5 marks  │
│    - session_start() usage                     │            │
│    - Setting session variables                 │            │
│    - Modifying session variables               │            │
│    - Code examples                             │            │
│                                                │            │
│ 3. Destroying Sessions                         │ 2.5 marks  │
│    - Clearing session variables                │            │
│    - Removing session cookie                   │            │
│    - session_destroy() usage                   │            │
│    - Complete multi-page example               │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Three Major Components (Section 2.3, Pattern 1)

b) Explain CREATE, INSERT and SELECT operations on MySQL table with example. (7 marks)

Answer:

MySQL is a relational database management system. PHP can interact with MySQL databases to create tables, insert data, and retrieve information. We'll use PDO (PHP Data Objects) which is the modern, secure, and recommended approach.


1. CREATE Operation

Creates a new table in the database with specified columns and data types.

SQL Syntax:

CREATE TABLE table_name (
    column1 datatype constraints,
    column2 datatype constraints,
    ...
);

Common Data Types:

  • INT - Integer numbers
  • VARCHAR(n) - Variable-length string (max n characters)
  • TEXT - Long text
  • DATE - Date (YYYY-MM-DD)
  • DATETIME - Date and time
  • DECIMAL(m,d) - Decimal number (m total digits, d after decimal)

Common Constraints:

  • PRIMARY KEY - Unique identifier for rows
  • AUTO_INCREMENT - Automatically generates unique numbers
  • NOT NULL - Column cannot be empty
  • UNIQUE - All values must be unique
  • DEFAULT value - Default value if none provided

PHP Example - CREATE Table:

<?php
try {
    // 1. Establish PDO database connection
    $dsn = "mysql:host=localhost;dbname=school_db;charset=utf8mb4";
    $username = "root";
    $password = "";
    $options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ];

    $pdo = new PDO($dsn, $username, $password, $options);

    // 2. CREATE TABLE SQL statement
    $sql = "CREATE TABLE students (
        student_id INT AUTO_INCREMENT PRIMARY KEY,
        first_name VARCHAR(50) NOT NULL,
        last_name VARCHAR(50) NOT NULL,
        email VARCHAR(100) UNIQUE NOT NULL,
        age INT,
        enrollment_date DATE,
        grade VARCHAR(10) DEFAULT 'Pending'
    )";

    // 3. Execute the CREATE statement
    $pdo->exec($sql);

    echo "<h3>✓ Table 'students' created successfully!</h3>";

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

Explanation:

  • student_id: Auto-incrementing primary key (unique identifier)
  • first_name, last_name: Required text fields (VARCHAR with NOT NULL)
  • email: Unique email address (no duplicates allowed)
  • age: Optional integer field
  • enrollment_date: Stores date values
  • grade: Has default value 'Pending'

2. INSERT Operation

Adds new rows (records) to a table.

SQL Syntax:

INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);

PHP Example - INSERT Data with Prepared Statements:

<?php
try {
    // PDO Connection (same as above)
    $dsn = "mysql:host=localhost;dbname=school_db;charset=utf8mb4";
    $pdo = new PDO($dsn, "root", "", [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);

    echo "<h2>INSERT Operations</h2>";

    // Method 1: INSERT single record with named parameters
    $sql = "INSERT INTO students (first_name, last_name, email, age, enrollment_date, grade)
            VALUES (:first_name, :last_name, :email, :age, :enrollment_date, :grade)";

    $stmt = $pdo->prepare($sql);

    // Execute with named parameters
    $result = $stmt->execute([
        ':first_name' => 'Alice',
        ':last_name' => 'Johnson',
        ':email' => 'alice.j@example.com',
        ':age' => 20,
        ':enrollment_date' => '2024-01-15',
        ':grade' => 'A'
    ]);

    if ($result) {
        echo "<p>✓ Alice Johnson inserted successfully!</p>";
        echo "<p>Inserted ID: " . $pdo->lastInsertId() . "</p>";
    }

    // Method 2: INSERT another record
    $stmt->execute([
        ':first_name' => 'Bob',
        ':last_name' => 'Smith',
        ':email' => 'bob.smith@example.com',
        ':age' => 22,
        ':enrollment_date' => '2024-01-16',
        ':grade' => 'B+'
    ]);
    echo "<p>✓ Bob Smith inserted successfully!</p>";

    // Method 3: INSERT with some optional fields omitted
    $sql2 = "INSERT INTO students (first_name, last_name, email, enrollment_date)
             VALUES (:first_name, :last_name, :email, :enrollment_date)";

    $stmt2 = $pdo->prepare($sql2);
    $stmt2->execute([
        ':first_name' => 'Charlie',
        ':last_name' => 'Brown',
        ':email' => 'charlie.b@example.com',
        ':enrollment_date' => '2024-01-17'
    ]);
    echo "<p>✓ Charlie Brown inserted (grade will be 'Pending' by default)</p>";

    // Method 4: INSERT multiple records efficiently
    $students = [
        ['Diana', 'Prince', 'diana.p@example.com', 21, '2024-01-18', 'A'],
        ['Eve', 'Taylor', 'eve.t@example.com', 19, '2024-01-19', 'B'],
        ['Frank', 'Wilson', 'frank.w@example.com', 23, '2024-01-20', 'C+']
    ];

    $sql3 = "INSERT INTO students (first_name, last_name, email, age, enrollment_date, grade)
             VALUES (?, ?, ?, ?, ?, ?)";
    $stmt3 = $pdo->prepare($sql3);

    foreach ($students as $student) {
        $stmt3->execute($student);
    }
    echo "<p>✓ Multiple students inserted successfully!</p>";

    echo "<h3>Total students inserted: " . count($students) + 3 . "</h3>";

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

Key Points:

  • Prepared Statements: Protect against SQL injection attacks
  • Named Parameters (:name): More readable, can reuse statement
  • Positional Parameters (?): Shorter syntax, order-dependent
  • lastInsertId(): Returns the ID of the last inserted record
  • DEFAULT values: Columns with defaults don't need values provided

3. SELECT Operation

Retrieves data from one or more tables.

SQL Syntax:

SELECT column1, column2, ... FROM table_name WHERE condition;
SELECT * FROM table_name;  -- Select all columns

PHP Example - SELECT Data:

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

    echo "<h2>SELECT Operations</h2>";

    // Example 1: SELECT all records, all columns
    echo "<h3>1. All Students:</h3>";
    $sql = "SELECT * FROM students";
    $stmt = $pdo->query($sql);
    $students = $stmt->fetchAll();

    echo "<table border='1' cellpadding='10'>";
    echo "<tr><th>ID</th><th>First Name</th><th>Last Name</th><th>Email</th><th>Age</th><th>Enrollment Date</th><th>Grade</th></tr>";

    foreach ($students as $student) {
        echo "<tr>";
        echo "<td>" . $student['student_id'] . "</td>";
        echo "<td>" . $student['first_name'] . "</td>";
        echo "<td>" . $student['last_name'] . "</td>";
        echo "<td>" . $student['email'] . "</td>";
        echo "<td>" . $student['age'] . "</td>";
        echo "<td>" . $student['enrollment_date'] . "</td>";
        echo "<td>" . $student['grade'] . "</td>";
        echo "</tr>";
    }
    echo "</table>";

    // Example 2: SELECT specific columns
    echo "<h3>2. Names and Emails Only:</h3>";
    $sql = "SELECT first_name, last_name, email FROM students";
    $stmt = $pdo->query($sql);

    while ($row = $stmt->fetch()) {
        echo "<p>" . $row['first_name'] . " " . $row['last_name'] . " - " . $row['email'] . "</p>";
    }

    // Example 3: SELECT with WHERE clause (using prepared statement)
    echo "<h3>3. Students with Grade 'A':</h3>";
    $sql = "SELECT * FROM students WHERE grade = :grade";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([':grade' => 'A']);

    while ($student = $stmt->fetch()) {
        echo "<p>" . $student['first_name'] . " " . $student['last_name'] . " - Grade: " . $student['grade'] . "</p>";
    }

    // Example 4: SELECT with multiple conditions
    echo "<h3>4. Students aged 20 or older:</h3>";
    $sql = "SELECT first_name, last_name, age FROM students WHERE age >= :min_age ORDER BY age";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([':min_age' => 20]);

    foreach ($stmt->fetchAll() as $student) {
        echo "<p>" . $student['first_name'] . " " . $student['last_name'] . " (Age: " . $student['age'] . ")</p>";
    }

    // Example 5: SELECT with COUNT
    echo "<h3>5. Total Number of Students:</h3>";
    $sql = "SELECT COUNT(*) as total FROM students";
    $stmt = $pdo->query($sql);
    $result = $stmt->fetch();
    echo "<p>Total students: " . $result['total'] . "</p>";

    // Example 6: SELECT single record
    echo "<h3>6. Find Student by Email:</h3>";
    $sql = "SELECT * FROM students WHERE email = :email";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([':email' => 'alice.j@example.com']);
    $student = $stmt->fetch();

    if ($student) {
        echo "<p><strong>Found:</strong> " . $student['first_name'] . " " . $student['last_name'] . "</p>";
        echo "<p>Student ID: " . $student['student_id'] . "</p>";
        echo "<p>Grade: " . $student['grade'] . "</p>";
    } else {
        echo "<p>Student not found!</p>";
    }

    // Example 7: SELECT with LIKE (pattern matching)
    echo "<h3>7. Students with 'son' in last name:</h3>";
    $sql = "SELECT first_name, last_name FROM students WHERE last_name LIKE :pattern";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([':pattern' => '%son%']);

    foreach ($stmt->fetchAll() as $student) {
        echo "<p>" . $student['first_name'] . " " . $student['last_name'] . "</p>";
    }

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

Complete Example - All Three Operations Together:

<?php
try {
    // Database connection
    $dsn = "mysql:host=localhost;dbname=school_db;charset=utf8mb4";
    $pdo = new PDO($dsn, "root", "", [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);

    echo "<h1>MySQL Operations: CREATE, INSERT, SELECT</h1>";

    // ==================== CREATE ====================
    echo "<h2>1. CREATE Operation</h2>";

    // Drop table if exists (for testing purposes)
    $pdo->exec("DROP TABLE IF EXISTS employees");

    // Create table
    $createSQL = "CREATE TABLE employees (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        position VARCHAR(50),
        salary DECIMAL(10, 2),
        hire_date DATE,
        department VARCHAR(50) DEFAULT 'General'
    )";

    $pdo->exec($createSQL);
    echo "<p>✓ Table 'employees' created successfully</p>";

    // ==================== INSERT ====================
    echo "<h2>2. INSERT Operation</h2>";

    $insertSQL = "INSERT INTO employees (name, position, salary, hire_date, department)
                  VALUES (:name, :position, :salary, :hire_date, :department)";

    $stmt = $pdo->prepare($insertSQL);

    // Insert multiple employees
    $employees = [
        ['John Doe', 'Manager', 75000.00, '2023-01-15', 'Sales'],
        ['Jane Smith', 'Developer', 65000.00, '2023-02-20', 'IT'],
        ['Bob Johnson', 'Designer', 55000.00, '2023-03-10', 'Marketing'],
        ['Alice Brown', 'Analyst', 60000.00, '2023-04-05', 'Finance'],
        ['Charlie Wilson', 'Developer', 70000.00, '2023-05-12', 'IT']
    ];

    foreach ($employees as $index => $emp) {
        $stmt->execute([
            ':name' => $emp[0],
            ':position' => $emp[1],
            ':salary' => $emp[2],
            ':hire_date' => $emp[3],
            ':department' => $emp[4]
        ]);
        echo "<p>✓ Inserted: {$emp[0]}</p>";
    }

    // ==================== SELECT ====================
    echo "<h2>3. SELECT Operations</h2>";

    // 3a. Select all employees
    echo "<h3>a) All Employees:</h3>";
    $selectSQL = "SELECT * FROM employees ORDER BY id";
    $stmt = $pdo->query($selectSQL);

    echo "<table border='1' cellpadding='8' style='border-collapse: collapse;'>";
    echo "<tr style='background-color: #4CAF50; color: white;'>";
    echo "<th>ID</th><th>Name</th><th>Position</th><th>Salary</th><th>Hire Date</th><th>Department</th></tr>";

    while ($row = $stmt->fetch()) {
        echo "<tr>";
        echo "<td>{$row['id']}</td>";
        echo "<td>{$row['name']}</td>";
        echo "<td>{$row['position']}</td>";
        echo "<td>$" . number_format($row['salary'], 2) . "</td>";
        echo "<td>{$row['hire_date']}</td>";
        echo "<td>{$row['department']}</td>";
        echo "</tr>";
    }
    echo "</table>";

    // 3b. Select IT department employees
    echo "<h3>b) IT Department Employees:</h3>";
    $sql = "SELECT name, position, salary FROM employees WHERE department = :dept";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([':dept' => 'IT']);

    foreach ($stmt->fetchAll() as $emp) {
        echo "<p>{$emp['name']} - {$emp['position']} - $" . number_format($emp['salary'], 2) . "</p>";
    }

    // 3c. Count employees
    echo "<h3>c) Statistics:</h3>";
    $sql = "SELECT
                COUNT(*) as total_employees,
                AVG(salary) as avg_salary,
                MAX(salary) as max_salary,
                MIN(salary) as min_salary
            FROM employees";
    $stmt = $pdo->query($sql);
    $stats = $stmt->fetch();

    echo "<p>Total Employees: {$stats['total_employees']}</p>";
    echo "<p>Average Salary: $" . number_format($stats['avg_salary'], 2) . "</p>";
    echo "<p>Highest Salary: $" . number_format($stats['max_salary'], 2) . "</p>";
    echo "<p>Lowest Salary: $" . number_format($stats['min_salary'], 2) . "</p>";

} catch (PDOException $e) {
    die("<p style='color: red;'>Database Error: " . $e->getMessage() . "</p>");
}
?>

Summary Table:

Operation Purpose SQL Example PHP Method
CREATE Create new table CREATE TABLE name (...) $pdo->exec($sql)
INSERT Add new records INSERT INTO table VALUES (...) $stmt->execute([...])
SELECT Retrieve data SELECT * FROM table WHERE ... $stmt->fetch() or $stmt->fetchAll()

PDO Fetch Methods:

Method Returns Use Case
fetch() Single row Loop through results one by one
fetchAll() All rows as array Get all results at once
fetchColumn() Single column value Get specific column from one row
rowCount() Number of affected rows Check how many rows were affected

Key Points:

  • PDO is modern and secure: Supports prepared statements, prevents SQL injection
  • Prepared statements are mandatory for queries with user input
  • Named parameters (:name) are more readable than positional (?)
  • CREATE: Uses exec() for DDL statements
  • INSERT: Uses prepare() + execute() with parameters
  • SELECT: Uses query() for simple queries, prepare() + execute() for parameterized queries
  • Always use try-catch for database operations
  • Fetch modes: FETCH_ASSOC (associative array), FETCH_OBJ (object), FETCH_NUM (numeric array)

Mark Distribution (Part b):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 18b - MARK DISTRIBUTION (Total: 7 marks)          │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. CREATE Operation                            │ 2.5 marks  │
│    - CREATE TABLE syntax                       │            │
│    - Column definitions and constraints        │            │
│    - Complete example with PDO                 │            │
│                                                │            │
│ 2. INSERT Operation                            │ 2 marks    │
│    - INSERT statement syntax                   │            │
│    - Prepared statements with parameters       │            │
│    - Multiple row insertion examples           │            │
│                                                │            │
│ 3. SELECT Operation                            │ 2.5 marks  │
│    - SELECT statement syntax                   │            │
│    - Fetching data (fetch, fetchAll)           │            │
│    - WHERE clause and filtering                │            │
│    - Complete working example                  │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Three Major Operations (Section 2.3, Pattern 1)

Overall Question 18 Total: 14 marks (7 + 7)


Module V — Module V
Question 19 (14 marks)

a) Explain the control structures in Blade Templating. (8 marks)

Answer:

Definition:

Blade is Laravel's powerful, simple, and elegant templating engine that provides a clean, intuitive way to work with PHP control statements in views. Unlike plain PHP templates, Blade templates are compiled into plain PHP code and cached for performance.

Key Blade Control Structures:

1. Conditional Statements (@if, @else, @elseif):

@if ($user->isAdmin())
    <p>Welcome, Administrator!</p>
@elseif ($user->isModerator())
    <p>Welcome, Moderator!</p>
@else
    <p>Welcome, User!</p>
@endif

@unless ($user->isSubscribed())
    <p>Please subscribe to premium.</p>
@endunless

2. Switch Statements:

@switch($role)
    @case('admin')
        <p>Administrator Dashboard</p>
        @break
    @case('user')
        <p>User Dashboard</p>
        @break
    @default
        <p>Guest Dashboard</p>
@endswitch

3. Loops:

For Loop:

@for ($i = 0; $i < 10; $i++)
    <p>Number: {{ $i }}</p>
@endfor

Foreach Loop:

@foreach ($users as $user)
    <p>{{ $user->name }}</p>
@endforeach

Forelse Loop (with empty handling):

@forelse ($posts as $post)
    <h3>{{ $post->title }}</h3>
@empty
    <p>No posts found.</p>
@endforelse

While Loop:

@while ($count < 10)
    <p>Count: {{ $count++ }}</p>
@endwhile

4. Loop Variable Properties:

The $loop variable is available inside loops:

  • $loop->index - Current iteration (0-based)
  • $loop->iteration - Current iteration (1-based)
  • $loop->first - Is first iteration
  • $loop->last - Is last iteration
  • $loop->count - Total items
@foreach ($items as $item)
    <div class="{{ $loop->odd ? 'odd' : 'even' }}">
        Item {{ $loop->iteration }} of {{ $loop->count }}
    </div>
@endforeach

5. Loop Control:

@foreach ($users as $user)
    @continue($user->isInactive())
    @break($loop->iteration > 10)
    <p>{{ $user->name }}</p>
@endforeach

6. Authentication Directives:

@auth
    <p>Welcome, {{ Auth::user()->name }}</p>
@endauth

@guest
    <p>Please login</p>
@endguest

Key Features:

  • Clean syntax without excessive PHP tags
  • Compiled to plain PHP for performance
  • Template inheritance with @extends, @section, @yield
  • Component-based architecture
  • Automatic XSS protection with {{ }}

Mark Distribution (Part a):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 19a - MARK DISTRIBUTION (Total: 8 marks)          │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ Complete Blade Control Structures Explanation  │ 8 marks    │
│    - Conditional directives (@if, @unless,     │            │
│      @switch) with examples (3)                │            │
│    - Loop directives (@for, @foreach, @while,  │            │
│      @forelse) with examples (3)               │            │
│    - Other control structures (@isset, @empty, │            │
│      @auth) with examples (2)                  │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Multiple Components - Topic-based (Section 3.2, Pattern 3)

b) Explain the methods of Laravel's resource controllers. (6 marks)

Answer:

Definition:

Resource controllers in Laravel provide a convenient way to build RESTful controllers for CRUD operations. A single route definition creates seven resourceful routes automatically.

Creating Resource Controller:

php artisan make:controller PostController --resource

Seven Resource Methods:

1. index() - Display all resources

  • HTTP: GET
  • Route: /posts
  • Purpose: List all records
public function index()
{
    $posts = Post::all();
    return view('posts.index', compact('posts'));
}

2. create() - Show create form

  • HTTP: GET
  • Route: /posts/create
  • Purpose: Display form to create new record
public function create()
{
    return view('posts.create');
}

3. store() - Save new resource

  • HTTP: POST
  • Route: /posts
  • Purpose: Process form and save data
public function store(Request $request)
{
    $validated = $request->validate([
        'title' => 'required',
        'content' => 'required'
    ]);

    Post::create($validated);
    return redirect()->route('posts.index');
}

4. show() - Display single resource

  • HTTP: GET
  • Route: /posts/{post}
  • Purpose: Show one record
public function show(Post $post)
{
    return view('posts.show', compact('post'));
}

5. edit() - Show edit form

  • HTTP: GET
  • Route: /posts/{post}/edit
  • Purpose: Display form to edit record
public function edit(Post $post)
{
    return view('posts.edit', compact('post'));
}

6. update() - Update resource

  • HTTP: PUT/PATCH
  • Route: /posts/{post}
  • Purpose: Process form and update data
public function update(Request $request, Post $post)
{
    $validated = $request->validate([
        'title' => 'required',
        'content' => 'required'
    ]);

    $post->update($validated);
    return redirect()->route('posts.show', $post);
}

7. destroy() - Delete resource

  • HTTP: DELETE
  • Route: /posts/{post}
  • Purpose: Delete record
public function destroy(Post $post)
{
    $post->delete();
    return redirect()->route('posts.index');
}

Route Registration:

// routes/web.php
Route::resource('posts', PostController::class);

This single line creates all seven routes automatically.

Summary Table:

Method HTTP URI Purpose
index GET /posts List all
create GET /posts/create Show create form
store POST /posts Save new
show GET /posts/{id} Display one
edit GET /posts/{id}/edit Show edit form
update PUT/PATCH /posts/{id} Update
destroy DELETE /posts/{id} Delete

Mark Distribution (Part b):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 19b - MARK DISTRIBUTION (Total: 6 marks)          │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ Laravel Resource Controller Methods            │ 6 marks    │
│    - Definition and purpose (1)                │            │
│    - Seven RESTful methods explanation:        │            │
│      - index() method (0.7)                    │            │
│      - create() method (0.7)                   │            │
│      - store() method (0.7)                    │            │
│      - show() method (0.7)                     │            │
│      - edit() method (0.7)                     │            │
│      - update() method (0.7)                   │            │
│      - destroy() method (0.8)                  │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Multiple Methods - CRUD Operations (Section 3.2, Pattern 3)

Overall Question 19 Total: 14 marks (8 + 6)


Question 20 (14 marks)

a) What is Route Model Binding in Laravel? Which types of route model binding are supported in Laravel? (6 marks)

Answer:

Definition:

Route Model Binding is a Laravel feature that automatically injects model instances into route callbacks or controller methods based on route parameters, eliminating the need to manually query the database.

Benefits:

  • Cleaner, more readable code
  • Automatic 404 responses for missing models
  • Less boilerplate code
  • Type-hinted model instances

Types of Route Model Binding:

1. Implicit Binding

Laravel automatically resolves model instances when the route parameter name matches the controller method's type-hinted parameter.

Example:

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

// Controller - WITHOUT binding
public function show($id)
{
    $post = Post::findOrFail($id);  // Manual query
    return view('posts.show', compact('post'));
}

// Controller - WITH implicit binding
public function show(Post $post)
{
    // $post is automatically injected!
    return view('posts.show', compact('post'));
}

Custom Key:

By default uses id column. Can be customized in model:

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

// Now routes work like: /posts/my-first-post

2. Explicit Binding

Manually define how Laravel resolves route parameters in RouteServiceProvider.

Example:

// app/Providers/RouteServiceProvider.php
public function boot()
{
    parent::boot();

    // Method 1: Simple binding
    Route::model('post', Post::class);

    // Method 2: Custom logic with closure
    Route::bind('user', function ($value) {
        return User::where('username', $value)->firstOrFail();
    });

    // Method 3: Complex resolution
    Route::bind('post', function ($value) {
        return Post::where('id', $value)
            ->orWhere('slug', $value)
            ->firstOrFail();
    });
}

Comparison:

Aspect Implicit Explicit
Setup Automatic Manual in RouteServiceProvider
Parameter naming Must match model name Any name
Resolution Standard findOrFail() Custom closure logic
Use case Simple queries Complex queries

Advanced Features:

Scoped Bindings:

// Ensure comment belongs to post
Route::get('/posts/{post}/comments/{comment}', function (Post $post, Comment $comment) {
    return $comment;
})->scopeBindings();

Complete Example:

// routes/web.php
Route::get('/users/{user}/posts', function (User $user) {
    return $user->posts;
});

// With explicit binding by username
// app/Providers/RouteServiceProvider.php
Route::bind('user', function ($value) {
    return User::where('username', $value)->firstOrFail();
});

// URL: /users/johndoe/posts (username instead of ID)

Key Points:

  • Two types: Implicit (automatic) and Explicit (manual configuration)
  • Implicit uses parameter name matching
  • Explicit allows custom resolution logic
  • Reduces repetitive findOrFail() calls
  • Automatic 404 handling
  • Can customize lookup column via model method

Mark Distribution (Part a):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 20a - MARK DISTRIBUTION (Total: 6 marks)          │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. Route Model Binding Definition              │ 2 marks    │
│    - What is Route Model Binding               │            │
│    - Benefits and purpose                      │            │
│                                                │            │
│ 2. Implicit Binding                            │ 2 marks    │
│    - How implicit binding works                │            │
│    - Complete code example                     │            │
│                                                │            │
│ 3. Explicit Binding                            │ 2 marks    │
│    - How explicit binding works                │            │
│    - RouteServiceProvider example              │            │
│    - Custom resolution logic                   │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Definition + Two Types (Section 2.2, Pattern 1)

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

Answer:

Part 1: JSON Data Types

JSON supports six data types:

1. String - Text in double quotes

{"name": "John Doe", "email": "john@example.com"}

2. Number - Integer or decimal (no quotes)

{"age": 25, "price": 99.99, "quantity": 100}

3. Boolean - true or false (lowercase, no quotes)

{"isActive": true, "isVerified": false}

4. Null - Null value (lowercase, no quotes)

{"middleName": null, "deletedAt": null}

5. Object - Key-value pairs in curly braces

{
    "user": {
        "name": "Alice",
        "age": 30,
        "address": {
            "city": "NYC",
            "zip": "10001"
        }
    }
}

6. Array - Ordered list in square brackets

{
    "numbers": [1, 2, 3, 4, 5],
    "fruits": ["apple", "banana", "orange"],
    "mixed": [1, "text", true, null]
}

Complete Example with All Types:

{
    "company": "Tech Corp",
    "founded": 2010,
    "revenue": 1500000.50,
    "isPublic": true,
    "CEO": null,
    "departments": ["Engineering", "Marketing", "Sales"],
    "headquarters": {
        "city": "San Francisco",
        "employees": 250
    }
}

Part 2: JSON.parse() and JSON.stringify() Functions

JSON.parse() - Convert JSON string to JavaScript object

Syntax: JSON.parse(jsonString)

Examples:

// Example 1: Basic parsing
const jsonString = '{"name": "John", "age": 30}';
const obj = JSON.parse(jsonString);

console.log(obj.name);  // Output: John
console.log(obj.age);   // Output: 30

// Example 2: Parsing array
const jsonArray = '[1, 2, 3, 4, 5]';
const arr = JSON.parse(jsonArray);

console.log(arr[0]);    // Output: 1
console.log(arr.length); // Output: 5

// Example 3: Nested objects
const jsonNested = `{
    "user": {
        "name": "Alice",
        "hobbies": ["reading", "gaming"]
    }
}`;

const data = JSON.parse(jsonNested);
console.log(data.user.name);        // Output: Alice
console.log(data.user.hobbies[0]);  // Output: reading

// Example 4: Error handling
try {
    const invalid = '{name: "John"}'; // Invalid JSON
    const obj = JSON.parse(invalid);
} catch (error) {
    console.error("Parse error:", error.message);
}

JSON.stringify() - Convert JavaScript object to JSON string

Syntax: JSON.stringify(value, replacer, space)

Examples:

// Example 1: Basic stringification
const obj = {
    name: "John",
    age: 30,
    city: "New York"
};

const jsonString = JSON.stringify(obj);
console.log(jsonString);
// Output: {"name":"John","age":30,"city":"New York"}

// Example 2: Pretty print with indentation
const jsonPretty = JSON.stringify(obj, null, 2);
console.log(jsonPretty);
/* Output:
{
  "name": "John",
  "age": 30,
  "city": "New York"
}
*/

// Example 3: Filtering properties
const user = {
    name: "John",
    password: "secret123",
    email: "john@example.com"
};

const jsonFiltered = JSON.stringify(user, (key, value) => {
    if (key === 'password') return undefined;
    return value;
});

console.log(jsonFiltered);
// Output: {"name":"John","email":"john@example.com"}

// Example 4: Whitelist properties
const jsonWhitelist = JSON.stringify(user, ['name', 'email']);
console.log(jsonWhitelist);
// Output: {"name":"John","email":"john@example.com"}

Practical Use Cases:

1. AJAX/Fetch API:

// Sending data to server
const userData = {
    username: "john_doe",
    email: "john@example.com"
};

fetch('/api/users', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify(userData)  // Convert to JSON
})
.then(response => response.json())  // Parse response
.then(data => console.log(data));

2. Local Storage:

// Save to localStorage
const settings = {
    theme: "dark",
    language: "en"
};

localStorage.setItem('settings', JSON.stringify(settings));

// Retrieve from localStorage
const stored = localStorage.getItem('settings');
const parsedSettings = JSON.parse(stored);

console.log(parsedSettings.theme);  // Output: dark

3. Deep Copy:

const original = {
    name: "John",
    address: {
        city: "NYC"
    }
};

const copy = JSON.parse(JSON.stringify(original));

copy.address.city = "Boston";
console.log(original.address.city);  // Output: NYC (unchanged)

Summary:

Functions:

Function Purpose Input Output
JSON.parse() Convert JSON string to object JSON string JavaScript object
JSON.stringify() Convert object to JSON string JavaScript object JSON string

Key Points:

  • JSON.parse() deserializes (string → object)
  • JSON.stringify() serializes (object → string)
  • Both are built-in JavaScript functions
  • Used for data exchange, storage, and transmission
  • Functions and undefined values are omitted in stringify
  • Always use try-catch when parsing JSON
  • Pretty-print with JSON.stringify(obj, null, 2)

Mark Distribution (Part b):

┌─────────────────────────────────────────────────────────────┐
│ QUESTION 20b - MARK DISTRIBUTION (Total: 8 marks)          │
├─────────────────────────────────────────────────────────────┤
│ Component                                      │ Marks      │
├────────────────────────────────────────────────┼────────────┤
│ 1. JSON Data Types                             │ 3 marks    │
│    - String, Number, Boolean                   │            │
│    - Array, Object, Null                       │            │
│    - Examples for each type                    │            │
│                                                │            │
│ 2. JSON.parse() Function                       │ 2.5 marks  │
│    - Purpose and usage                         │            │
│    - Syntax and parameters                     │            │
│    - Complete code examples                    │            │
│                                                │            │
│ 3. JSON.stringify() Function                   │ 2.5 marks  │
│    - Purpose and usage                         │            │
│    - Syntax with formatting options            │            │
│    - Complete code examples                    │            │
│    - Pretty-printing demonstration             │            │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Concept + Two Functions (Section 2.2, Pattern 4)

Overall Question 20 Total: 14 marks (6 + 8)




END OF ANSWER KEY