CST463 Web Programming - Answer Key
CST463 Web Programming - Answer Key
November 2024 (B.Tech Degree S7 Examination)
Subject: Web Programming (CST463)
Date: November 2024
Total Marks: 100
Duration: 3 Hours
University: APJ Abdul Kalam Technological University
Scheme: 2019 Scheme
PART A (Short Answer Questions)
Answer all questions, each carries 3 marks.
Question 1 (3 marks) — What is the difference between web servers and browsers in the context of their implementation and functionality.
What is the difference between web servers and browsers in the context of their implementation and functionality.
Answer:
Web servers and browsers serve complementary but distinct roles in web architecture.
Web Servers:
- Software applications that store, process, and deliver web content to clients
- Handle HTTP requests from browsers and send HTTP responses
- Implement server-side technologies (PHP, Node.js, Python, etc.)
- Examples: Apache, Nginx, IIS, Tomcat
Browsers:
- Client-side applications that request, receive, and render web content
- Interpret and display HTML, CSS, and execute JavaScript
- Provide user interface for navigating the web
- Examples: Chrome, Firefox, Safari, Edge
Key Difference: Web servers handle backend processing and data storage, while browsers handle frontend rendering and user interaction.
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 1 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Web Servers - Implementation & Functionality│ 1.5 marks │
│ - Definition and role │ │
│ - HTTP request/response handling │ │
│ - Server-side technology support │ │
│ - Examples (Apache, Nginx, etc.) │ │
│ │ │
│ 2. Browsers - Implementation & Functionality │ 1.5 marks │
│ - Definition and role │ │
│ - HTML/CSS rendering & JS execution │ │
│ - User interface provision │ │
│ - Examples (Chrome, Firefox, etc.) │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Differentiate Two Concepts (1.5 + 1.5)
Reference: Section 1.2, Pattern 1 from CST463_Marking_Scheme_Pattern_Analysis.md
Question 2 (3 marks) — Write HTML code to design a web page to create a table with 3 rows and 3 columns for entering the mark list of 3 students. Assume suitable headings for each column.
Write HTML code to design a web page to create a table with 3 rows and 3 columns for entering the mark list of 3 students. Assume suitable headings for each column.
Answer:
<table border="1">
<tr>
<th>Student Name</th>
<th>Roll Number</th>
<th>Marks</th>
</tr>
<tr>
<td>John Doe</td>
<td>101</td>
<td>85</td>
</tr>
<tr>
<td>Mary Smith</td>
<td>102</td>
<td>92</td>
</tr>
<tr>
<td>Bob Johnson</td>
<td>103</td>
<td>78</td>
</tr>
</table>
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 2 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Complete HTML Table Code │ 3 marks │
│ - Table tag with border attribute │ │
│ - Header row with 3 column headings │ │
│ - Three data rows with 3 columns each │ │
│ - Proper use of <th> and <td> tags │ │
│ - Suitable data for student mark list │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Simple Programming Question - Full Marks
Reference: Section 1.2, Pattern 5 from CST463_Marking_Scheme_Pattern_Analysis.md
Question 3 (3 marks) — Write a JavaScript program to read an integer value using prompt and display its square.
Write a JavaScript program to read an integer value using prompt and display its square.
Answer:
// Read integer from user
let num = parseInt(prompt("Enter an integer:"));
// Calculate square
let square = num * num;
// Display result
document.write("The square of " + num + " is " + square);
// Alternative using alert
// alert("The square of " + num + " is " + square);
Explanation: The prompt() function reads user input as a string, parseInt() converts it to an integer, and the result is displayed using document.write() or alert().
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 3 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Complete JavaScript Program │ 3 marks │
│ - Using prompt() to read input │ │
│ - parseInt() for type conversion │ │
│ - Square calculation logic │ │
│ - Display using document.write()/alert() │ │
│ - Explanation of code functionality │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Simple Programming Question - Full Marks
Reference: Section 1.2, Pattern 5 from CST463_Marking_Scheme_Pattern_Analysis.md
Question 4 (3 marks) — What are the different ways of adjusting spacing in a text? Explain the various style attributes used for that.
What are the different ways of adjusting spacing in a text? Explain the various style attributes used for that.
Answer:
Text spacing in CSS can be adjusted using several style attributes:
Key Spacing Attributes:
-
letter-spacing: Controls space between characters
- Example:
letter-spacing: 2px;
- Example:
-
word-spacing: Controls space between words
- Example:
word-spacing: 5px;
- Example:
-
line-height: Controls vertical space between lines
- Example:
line-height: 1.5;
- Example:
-
text-indent: Controls indentation of first line
- Example:
text-indent: 20px;
- Example:
-
padding: Controls internal spacing within element
- Example:
padding: 10px;
- Example:
-
margin: Controls external spacing around element
- Example:
margin: 15px;
- Example:
Example:
p {
letter-spacing: 1px;
word-spacing: 3px;
line-height: 1.6;
}
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 4 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Text Spacing Methods (Any 3 methods) │ 3 marks │
│ Each spacing attribute explained: │ (1 each) │
│ - letter-spacing / word-spacing │ │
│ - line-height │ │
│ - text-indent │ │
│ - padding / margin │ │
│ (Answer provides 6 attributes - letter- │ │
│ spacing, word-spacing, line-height, │ │
│ text-indent, padding, margin with │ │
│ examples and CSS code) │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Multiple Equal Components (Any 3 @ 1 mark each)
Reference: Section 1.2, Pattern 4 from CST463_Marking_Scheme_Pattern_Analysis.md
Question 5 (3 marks) — Write a PHP program to check whether the given number is Armstrong or not.
Write a PHP program to check whether the given number is Armstrong or not.
Answer:
<?php
// Armstrong number: sum of cubes of digits equals the number itself
// Example: 153 = 1³ + 5³ + 3³ = 1 + 125 + 27 = 153
$num = 153;
$sum = 0;
$temp = $num;
// Calculate sum of cubes of digits
while ($temp != 0) {
$digit = $temp % 10;
$sum = $sum + ($digit * $digit * $digit);
$temp = (int)($temp / 10);
}
// Check if Armstrong number
if ($sum == $num) {
echo "$num is an Armstrong number";
} else {
echo "$num is not an Armstrong number";
}
?>
Explanation: An Armstrong number is equal to the sum of cubes of its digits. The program extracts each digit, cubes it, and adds to the sum, then compares with the original number.
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 5 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Armstrong Number Logic │ 1.5 marks │
│ - Understanding of Armstrong number concept │ │
│ - Algorithm: extract digits, cube, sum │ │
│ - Comparison logic │ │
│ │ │
│ 2. PHP Code Implementation │ 1.5 marks │
│ - Variable initialization │ │
│ - while loop for digit extraction │ │
│ - Cube calculation and sum accumulation │ │
│ - Conditional check and output │ │
│ - Explanation of code functionality │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Logic + Implementation (1.5 + 1.5)
Reference: Section 5.4 (PHP Questions - 3 marks) from CST463_Marking_Scheme_Pattern_Analysis.md
Question 6 (3 marks) — Memorize the two modes that the PHP processor operates in.
Memorize the two modes that the PHP processor operates in.
Answer:
The PHP processor operates in two distinct internal processing modes:
1. Copy Mode:
- When the PHP processor encounters standard HTML/XHTML in a PHP file (outside of PHP tags like
<?php ?>), it copies this code directly to the output without any processing - This is the default mode for handling static content
- Ensures that static parts of a web page (HTML headers, static content) don't incur additional processing overhead
- Example: Text outside
<?php ... ?>tags is directly copied to output
2. Interpreter Mode:
- Activated when PHP encounters the opening tag
<?php - PHP starts interpreting and executing the PHP code that follows
- Sends the script-generated output to the client
- Once PHP encounters the closing tag
?>), it switches back to copy mode - Processes PHP statements, functions, and expressions
- Output is generated using
echo,print, etc.
How Mode Switching Works:
The processor seamlessly switches between these two modes as it reads through the file, allowing for a mix of static and dynamic content within the same script.
Example:
This is Copy Mode - output directly
<?php
// This is Interpreter Mode
echo "Hello from Interpreter Mode";
?>
Back to Copy Mode - output directly
Note: These internal processing modes are distinct from execution environment modes like CGI, Module (mod_php), CLI, or FastCGI, which relate to how PHP interacts with the operating system and web server.
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 6 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Copy Mode │ 1.5 marks │
│ - Definition and functionality │ │
│ - When it activates (outside PHP tags) │ │
│ - Direct output mechanism │ │
│ - Example demonstration │ │
│ │ │
│ 2. Interpreter Mode │ 1.5 marks │
│ - Definition and functionality │ │
│ - When it activates (inside <?php ?> tags) │ │
│ - Code execution and output generation │ │
│ - Mode switching mechanism │ │
│ - Example demonstration │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Differentiate Two Concepts (1.5 + 1.5)
Reference: Section 1.2, Pattern 1 from CST463_Marking_Scheme_Pattern_Analysis.md
Question 7 (3 marks) — Justify the significance of sessions in web.
Justify the significance of sessions in web.
Answer:
Sessions are crucial for maintaining state and user-specific data across multiple HTTP requests in web applications.
Key Significance:
- State Management: HTTP is stateless; sessions preserve user data across page requests
- User Authentication: Track logged-in users and maintain authentication status
- Personalization: Store user preferences, shopping cart items, and customized settings
- Security: More secure than cookies as session data is stored server-side
- Data Persistence: Maintain temporary data throughout user's visit without database overhead
How it works:
- Server generates unique session ID for each user
- Session ID stored in cookie or URL parameter
- Server retrieves session data using this ID on subsequent requests
Example in PHP:
session_start();
$_SESSION['username'] = 'john_doe';
$_SESSION['cart_items'] = 5;
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 7 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Significance of Sessions (Explanation) │ 2 marks │
│ - State management in stateless HTTP │ │
│ - User authentication tracking │ │
│ - Personalization and data persistence │ │
│ - Security advantages over cookies │ │
│ - Session ID mechanism explanation │ │
│ │ │
│ 2. PHP Session Example │ 1 mark │
│ - session_start() demonstration │ │
│ - $_SESSION usage examples │ │
│ - Practical application shown │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Explanation + Example (2 + 1)
Reference: Section 1.2, Pattern 3 from CST463_Marking_Scheme_Pattern_Analysis.md
Question 8 (3 marks) — Illustrate with a sample PHP script, how INSERT operations on MySQL table are implemented in PHP.
Illustrate with a sample PHP script, how INSERT operations on MySQL table are implemented in PHP.
Answer:
<?php
// Database connection using PDO
$dsn = "mysql:host=localhost;dbname=student_db;charset=utf8mb4";
$username = "root";
$password = "";
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// INSERT operation using prepared statement
$sql = "INSERT INTO students (name, roll_no, marks) VALUES (:name, :roll, :marks)";
$stmt = $pdo->prepare($sql);
// Execute with data
$stmt->execute([
'name' => 'John Doe',
'roll' => '101',
'marks' => 85
]);
echo "Record inserted successfully";
} catch (PDOException $e) {
die("Error: " . $e->getMessage());
}
?>
Key Points:
- Uses PDO for database connection
- Prepared statements prevent SQL injection
- Named parameters (
:name,:roll,:marks) for security - Exception handling with try-catch
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 8 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. PDO Database Connection │ 1.5 marks │
│ - PDO connection establishment │ │
│ - Error mode configuration │ │
│ - Connection parameters (DSN, user, pass) │ │
│ │ │
│ 2. INSERT Operation with Prepared Statement │ 1.5 marks │
│ - SQL INSERT statement syntax │ │
│ - Prepared statement using prepare() │ │
│ - Named parameters (:name, :roll, :marks) │ │
│ - Execute with data array │ │
│ - Success message and exception handling │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Concept + Syntax (1.5 + 1.5)
Reference: Section 1.2, Pattern 6 from CST463_Marking_Scheme_Pattern_Analysis.md
Question 9 (3 marks) — List out the valid data types in JSON.
List out the valid data types in JSON.
Answer:
JSON (JavaScript Object Notation) supports six fundamental data types:
Valid JSON Data Types:
-
String: Text enclosed in double quotes
- Example:
"Hello World","John"
- Example:
-
Number: Integer or floating-point values
- Example:
42,3.14,-10
- Example:
-
Boolean: True or false values
- Example:
true,false
- Example:
-
Null: Represents empty or null value
- Example:
null
- Example:
-
Object: Collection of key-value pairs enclosed in
{}- Example:
{"name": "John", "age": 25}
- Example:
-
Array: Ordered list of values enclosed in
[]- Example:
[1, 2, 3, 4],["a", "b", "c"]
- Example:
Example combining data types:
{
"name": "Alice",
"age": 30,
"isStudent": true,
"grade": null,
"courses": ["Math", "Physics"],
"address": {"city": "Mumbai", "pin": 400001}
}
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 9 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. JSON Data Types (6 types @ 0.5 each) │ 3 marks │
│ - String with example │ (0.5 each) │
│ - Number with example │ │
│ - Boolean with example │ │
│ - Null with example │ │
│ - Object with example │ │
│ - Array with example │ │
│ - Comprehensive example combining types │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Multiple Equal Components (6 types @ 0.5 marks each)
Reference: Section 5.8 (JSON Questions - 3 marks) from CST463_Marking_Scheme_Pattern_Analysis.md
Question 10 (3 marks) — Explain the role of Resource controllers in Laravel.
Explain the role of Resource controllers in Laravel.
Answer:
Resource controllers in Laravel provide a convenient way to handle CRUD (Create, Read, Update, Delete) operations for a resource through RESTful conventions.
Key Features:
-
Automatic Route Generation: Single route declaration creates multiple endpoints
-
Predefined Methods: Seven standard methods for resource operations:
index()- Display list of resourcescreate()- Show form to create new resourcestore()- Save new resource to databaseshow($id)- Display specific resourceedit($id)- Show form to edit resourceupdate($id)- Update resource in databasedestroy($id)- Delete resource from database
-
RESTful Convention: Follows REST principles automatically
Example:
// Route definition
Route::resource('posts', PostController::class);
// Controller
class PostController extends Controller {
public function index() { /* List all posts */ }
public function store() { /* Save new post */ }
}
Benefits: Reduces boilerplate code, maintains consistency, and follows best practices.
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 10 - MARK DISTRIBUTION (Total: 3 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Resource Controllers Explanation │ 1.5 marks │
│ - Definition and purpose │ │
│ - CRUD operations handling │ │
│ - RESTful convention benefits │ │
│ │ │
│ 2. Methods and Syntax Example │ 1.5 marks │
│ - Seven standard methods listed │ │
│ - Route definition syntax │ │
│ - Controller code example │ │
│ - Benefits explanation │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Explanation + Syntax (1.5 + 1.5)
Reference: Section 5.9 (Laravel Questions - 3 marks) from CST463_Marking_Scheme_Pattern_Analysis.md
PART B (Long Answer Questions)
Answer any one full question from each module, each carries 14 marks.
MODULE I — ---
Question 11 (14 marks)
a) What is the difference between radio buttons and checkboxes when implemented using HTML? Write HTML code to implement a form which has the following elements: (8 marks)
- i. A textbox which can accept a maximum of 25 characters.
- ii. Three radio buttons.
- iii. A selection list containing four items, two which are always visible.
- iv. A submit button, clicking on which will prompt the browser to send the form data to the server "http://responses.mysite.com" using "POST" method.
Answer:
Difference between Radio Buttons and Checkboxes:
| Aspect | Radio Buttons | Checkboxes |
|---|---|---|
| Selection Type | Single selection only (mutually exclusive) | Multiple selections allowed |
| HTML Element | <input type="radio"> |
<input type="checkbox"> |
| Name Attribute | Same name for grouped options |
Can have different names |
| Use Case | Gender selection, Yes/No questions | Selecting multiple interests, preferences |
| Behavior | Selecting one deselects others in group | Each checkbox is independent |
Implementation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form with Radio Buttons and Selection List</title>
</head>
<body>
<h2>Student Registration Form</h2>
<form action="http://responses.mysite.com" method="POST">
<!-- Textbox with maximum 25 characters -->
<label for="username">Username (max 25 chars):</label><br>
<input type="text" id="username" name="username" maxlength="25" required><br><br>
<!-- Three radio buttons -->
<label>Select your course:</label><br>
<input type="radio" id="btech" name="course" value="B.Tech" required>
<label for="btech">B.Tech</label><br>
<input type="radio" id="mtech" name="course" value="M.Tech">
<label for="mtech">M.Tech</label><br>
<input type="radio" id="phd" name="course" value="PhD">
<label for="phd">PhD</label><br><br>
<!-- Selection list with 4 items, 2 always visible -->
<label for="department">Select Department:</label><br>
<select id="department" name="department" size="2" required>
<option value="cse">Computer Science</option>
<option value="ece">Electronics</option>
<option value="mech">Mechanical</option>
<option value="civil">Civil Engineering</option>
</select><br><br>
<!-- Submit button -->
<button type="submit">Submit Form</button>
</form>
</body>
</html>
Key Features Explained:
- maxlength="25": Restricts textbox to 25 characters maximum
- name="course": Same name groups radio buttons for single selection
- size="2": Makes selection list show 2 items simultaneously (scrollable for others)
- action and method: Sends form data to specified URL using POST method
Mark Distribution for Question 11(a):
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 11(a) - MARK DISTRIBUTION (Total: 8 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Difference between Radio & Checkbox │ 2 marks │
│ - Comparison table with key aspects │ │
│ - Selection type (single vs multiple) │ │
│ - HTML element types │ │
│ - Name attribute usage │ │
│ - Use cases and behavior │ │
│ │ │
│ 2. HTML Form Implementation │ 6 marks │
│ a) Textbox with maxlength=25 │ 1.5 marks │
│ - Input type="text" │ │
│ - maxlength attribute │ │
│ - Label and proper structure │ │
│ │ │
│ b) Three Radio Buttons │ 1.5 marks │
│ - Three input type="radio" elements │ │
│ - Same name attribute for grouping │ │
│ - Labels for each option │ │
│ │ │
│ c) Selection List (4 items, 2 visible) │ 2 marks │
│ - <select> tag with size="2" │ │
│ - Four <option> elements │ │
│ - Proper label │ │
│ │ │
│ d) Submit Button with POST method │ 1 mark │
│ - Form action attribute │ │
│ - method="POST" │ │
│ - Submit button │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Multiple Sub-Components (2 + 6 breakdown)
Reference: Section 3.2, Pattern 4 & Section 5.1 (HTML Form Questions)
from CST463_Marking_Scheme_Pattern_Analysis.md
b) Write down any four HTML tags and their purpose with suitable examples. What are tag attributes? (6 marks)
Answer:
Four HTML Tags with Purpose and Examples:
1. <p> - Paragraph Tag
- Purpose: Defines a paragraph of text with automatic spacing before and after
- Example:
<p>This is a paragraph containing some text content.</p> <p>This is another paragraph with additional information.</p>
2. <div> - Division/Container Tag
- Purpose: Creates a container or section for grouping other HTML elements, commonly used for layout and styling
- Example:
<div class="header"> <h1>Welcome to My Website</h1> <p>This content is grouped inside a div container</p> </div>
3. <img> - Image Tag
- Purpose: Embeds an image into the web page
- Example:
<img src="profile.jpg" alt="User Profile Picture" width="200" height="150">
4. <strong> - Strong Emphasis Tag
- Purpose: Indicates strong importance, typically displayed as bold text
- Example:
<p>This is <strong>very important</strong> information.</p>
What are Tag Attributes?
Tag attributes provide additional information about HTML elements and modify their behavior or appearance.
Characteristics:
- Attributes are specified within the opening tag
- Format:
attribute="value" - Multiple attributes can be added to a single tag
- Some attributes are required (e.g.,
srcin<img>), others are optional
Common Attributes:
- id: Unique identifier for an element
- class: Assigns CSS class for styling
- style: Inline CSS styling
- src: Source file path (for images, scripts)
- href: Hyperlink reference (for links)
- alt: Alternative text description
- width, height: Dimensions of elements
Example with Multiple Attributes:
<img src="photo.jpg" alt="Sunset" width="300" height="200" id="mainImage" class="responsive">
Mark Distribution for Question 11(b):
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 11(b) - MARK DISTRIBUTION (Total: 6 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Four HTML Tags (1 mark each) │ 4 marks │
│ a) <p> tag - Purpose & Example │ 1 mark │
│ - Paragraph definition │ │
│ - Code example with usage │ │
│ │ │
│ b) <div> tag - Purpose & Example │ 1 mark │
│ - Container/division explanation │ │
│ - Code example with usage │ │
│ │ │
│ c) <img> tag - Purpose & Example │ 1 mark │
│ - Image embedding explanation │ │
│ - Code example with attributes │ │
│ │ │
│ d) <strong> tag - Purpose & Example │ 1 mark │
│ - Strong emphasis explanation │ │
│ - Code example with usage │ │
│ │ │
│ 2. Tag Attributes Explanation │ 2 marks │
│ - Definition of attributes │ │
│ - Characteristics (format, placement) │ │
│ - Common attributes listed │ │
│ - Example with multiple attributes │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Multiple Equal Parts (4 tags) + Concept (attributes)
Reference: Section 2.2, Pattern 3 (6-mark questions)
from CST463_Marking_Scheme_Pattern_Analysis.md
Question 12 (14 marks)
a) Differentiate between "rowspan" and "colspan" table attributes. Write HTML code to create a table whose structure is as below: Insert any text of your choice in the table cells. The first row is considered to be containing a heading. The background colour for the table should be red, and the text in the cells should all be centre aligned. (6 marks)
Answer:
Difference between Rowspan and Colspan:
| Attribute | Purpose | Effect | Example Use |
|---|---|---|---|
| rowspan | Merges cells vertically | Cell spans across multiple rows | Header spanning multiple rows below |
| colspan | Merges cells horizontally | Cell spans across multiple columns | Header spanning multiple columns across |
| Syntax | rowspan="number" |
Extends cell downward | <td rowspan="3">Data</td> |
| Syntax | colspan="number" |
Extends cell rightward | <td colspan="2">Data</td> |
Table Structure Reference (Markdown):
| Student ID | Information |
|------------|-----------------------------|
| Name | John Doe |
| Roll No | 101 |
| Course | B.Tech CSE |
| Address | Department: Engineering |
| | Contact: +91-9876543210 |
| | Email: john.doe@example.com |
| Status | Active |
HTML Table Implementation:
Looking at the table structure in the question diagram, the table has 8 rows total with ONLY ONE rowspan section:
- Row 1: Header row with 2 cells (no colspan)
- Rows 2-4: Three regular rows with 2 cells each
- Rows 5-7: First column cell spans 3 rows vertically (rowspan="3"), with individual cells on the right
- Row 8: Two regular cells
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table with Rowspan and Colspan</title>
</head>
<body>
<table border="1" bgcolor="red" align="center" width="50%">
<!-- Row 1: Heading row with two header cells -->
<tr>
<th style="text-align: center; color: white; padding: 10px;">
Student ID
</th>
<th style="text-align: center; color: white; padding: 10px;">
Information
</th>
</tr>
<!-- Row 2: Regular row with two cells -->
<tr>
<td style="text-align: center; color: white; padding: 10px;">
Name
</td>
<td style="text-align: center; color: white; padding: 10px;">
John Doe
</td>
</tr>
<!-- Row 3: Regular row with two cells -->
<tr>
<td style="text-align: center; color: white; padding: 10px;">
Roll No
</td>
<td style="text-align: center; color: white; padding: 10px;">
101
</td>
</tr>
<!-- Row 4: Regular row with two cells -->
<tr>
<td style="text-align: center; color: white; padding: 10px;">
Course
</td>
<td style="text-align: center; color: white; padding: 10px;">
B.Tech CSE
</td>
</tr>
<!-- Row 5: Left cell with rowspan=3 starts here -->
<tr>
<td rowspan="3" style="text-align: center; color: white; padding: 10px;">
Address
</td>
<td style="text-align: center; color: white; padding: 10px;">
Department: Engineering
</td>
</tr>
<!-- Row 6: Only right cell (left continues from row 5) -->
<tr>
<td style="text-align: center; color: white; padding: 10px;">
Contact: +91-9876543210
</td>
</tr>
<!-- Row 7: Only right cell (left continues from row 5, rowspan ends) -->
<tr>
<td style="text-align: center; color: white; padding: 10px;">
Email: john.doe@example.com
</td>
</tr>
<!-- Row 8: Two regular cells -->
<tr>
<td style="text-align: center; color: white; padding: 10px;">
Status
</td>
<td style="text-align: center; color: white; padding: 10px;">
Active
</td>
</tr>
</table>
</body>
</html>
Explanation:
- bgcolor="red": Sets table background to red
- style="text-align: center": Centers all text in cells
- No colspan is used in this table
- Only ONE rowspan="3": The "Address" cell in the first column spans rows 5-7 vertically
- border="1": Displays table borders
- color: white: Makes text visible on red background
- Total: 8 rows with only one rowspan section (rows 5-7) as shown in the question diagram
Mark Distribution for Question 12(a):
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 12(a) - MARK DISTRIBUTION (Total: 6 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Differentiate Rowspan vs Colspan │ 2 marks │
│ - Comparison table with purpose │ │
│ - Effect and syntax explanation │ │
│ - Example use cases for both │ │
│ │ │
│ 2. HTML Table Implementation │ 4 marks │
│ - Complete table structure with DOCTYPE │ │
│ - bgcolor="red" attribute │ │
│ - text-align: center for all cells │ │
│ - Header row (first row) │ │
│ - Proper use of rowspan="3" │ │
│ - Complete 8-row table structure │ │
│ - Inline styling for center alignment │ │
│ - Proper cell content │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Difference (2) + Implementation (4)
Reference: Section 2.2, Pattern 3 & Section 5.1 (HTML Tables)
from CST463_Marking_Scheme_Pattern_Analysis.md
b) Explain following html tags with proper example: (8 marks)
1. <p> 2. <div> 3. <img> 4. <strong>
Answer:
1. <p> Tag - Paragraph Tag
Purpose: The <p> tag defines a paragraph in HTML. It automatically adds space before and after the content, creating visual separation between text blocks.
Characteristics:
- Block-level element (starts on new line)
- Browsers automatically add margin before and after paragraphs
- Used for organizing text content into logical sections
Example:
<!DOCTYPE html>
<html>
<head>
<title>Paragraph Example</title>
</head>
<body>
<p>Web programming is an essential skill for modern developers.</p>
<p>HTML forms the foundation of web pages, providing structure and content.</p>
<p>CSS is used for styling and layout, while JavaScript adds interactivity.</p>
</body>
</html>
Output: Each paragraph appears on a new line with spacing between them.
2. <div> Tag - Division/Container Tag
Purpose: The <div> tag is a generic container used to group and organize other HTML elements. It's primarily used for layout structure and applying CSS styles to sections of content.
Characteristics:
- Block-level element
- No semantic meaning (unlike
<header>,<footer>) - Essential for page layout and CSS styling
- Can contain any HTML elements
Example:
<!DOCTYPE html>
<html>
<head>
<title>Div Example</title>
<style>
.header {
background-color: #333;
color: white;
padding: 20px;
text-align: center;
}
.content {
background-color: #f4f4f4;
padding: 20px;
margin: 10px;
}
</style>
</head>
<body>
<div class="header">
<h1>Welcome to My Website</h1>
</div>
<div class="content">
<h2>About Us</h2>
<p>This section contains information about our company.</p>
</div>
<div class="content">
<h2>Services</h2>
<p>We provide web development and design services.</p>
</div>
</body>
</html>
Usage: Groups related elements for styling and layout management.
3. <img> Tag - Image Tag
Purpose: The <img> tag embeds images into web pages. It's a self-closing tag that displays graphics, photos, or illustrations.
Characteristics:
- Inline element (doesn't start on new line)
- Self-closing tag (no closing tag needed)
- Requires
srcattribute (image source path) - Should include
altattribute for accessibility
Important Attributes:
- src: Path to image file (required)
- alt: Alternative text description (required for accessibility)
- width, height: Image dimensions
- title: Tooltip text on hover
Example:
<!DOCTYPE html>
<html>
<head>
<title>Image Example</title>
</head>
<body>
<h2>University Campus</h2>
<!-- Image with all important attributes -->
<img src="campus.jpg"
alt="University main building"
width="600"
height="400"
title="Our beautiful campus">
<p>The image above shows our university campus.</p>
<!-- Responsive image -->
<img src="logo.png"
alt="University Logo"
style="max-width: 100%; height: auto;">
</body>
</html>
Best Practices:
- Always include
alttext for screen readers - Optimize image size for faster loading
- Use appropriate image formats (JPEG for photos, PNG for graphics)
4. <strong> Tag - Strong Importance Tag
Purpose: The <strong> tag indicates that text has strong importance or seriousness. Browsers typically render it as bold text, but its primary purpose is semantic meaning, not just visual styling.
Characteristics:
- Inline element
- Semantic meaning (indicates importance)
- Typically displayed as bold
- Better than
<b>tag for semantic HTML
Difference from <b> tag:
<strong>: Semantic emphasis (important content)<b>: Visual styling only (bold appearance)
Example:
<!DOCTYPE html>
<html>
<head>
<title>Strong Tag Example</title>
</head>
<body>
<h2>Safety Instructions</h2>
<p>
<strong>Warning:</strong> Do not touch electrical components with wet hands.
</p>
<p>
Please read the <strong>terms and conditions</strong> carefully before proceeding.
</p>
<p>
<strong>Important Notice:</strong> The exam will be held on November 15, 2024.
Students must carry their <strong>hall tickets</strong> and <strong>ID cards</strong>.
</p>
<h3>Instructions</h3>
<ul>
<li><strong>Step 1:</strong> Fill in your personal details</li>
<li><strong>Step 2:</strong> Upload required documents</li>
<li><strong>Step 3:</strong> Submit the application</li>
</ul>
</body>
</html>
Use Cases:
- Warnings and alerts
- Important keywords or phrases
- Emphasis on critical information
- Instructions and guidelines
CSS Styling Example:
<style>
strong {
color: red;
font-weight: bold;
text-decoration: underline;
}
</style>
Mark Distribution for Question 12(b):
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 12(b) - MARK DISTRIBUTION (Total: 8 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. <p> Tag - Paragraph │ 2 marks │
│ - Purpose and definition │ │
│ - Characteristics (block-level, spacing) │ │
│ - Complete code example with HTML structure │ │
│ - Output explanation │ │
│ │ │
│ 2. <div> Tag - Division/Container │ 2 marks │
│ - Purpose and definition │ │
│ - Characteristics (block-level, container) │ │
│ - Complete code example with CSS styling │ │
│ - Usage explanation │ │
│ │ │
│ 3. <img> Tag - Image │ 2 marks │
│ - Purpose and definition │ │
│ - Characteristics (inline, self-closing) │ │
│ - Important attributes (src, alt, etc.) │ │
│ - Complete code examples │ │
│ - Best practices │ │
│ │ │
│ 4. <strong> Tag - Strong Importance │ 2 marks │
│ - Purpose and semantic meaning │ │
│ - Characteristics (inline, emphasis) │ │
│ - Difference from <b> tag │ │
│ - Complete code examples │ │
│ - Use cases and CSS styling example │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Multiple Equal Examples (4 tags @ 2 marks each)
Reference: Section 3.2, Pattern 7 from CST463_Marking_Scheme_Pattern_Analysis.md
MODULE II — ---
Question 13 (14 marks)
a) Write CSS style rules to implement the following in a web page: (6 marks)
- i. Display the content of hyperlinks with yellow background colour and in italics
- ii. Display the contents of unordered lists in bold and in Arial font
- iii. Display a background image titled "birds.jpg" with no tiling.
Answer:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Styling Example</title>
<style>
/* i. Hyperlinks with yellow background and italics */
a {
background-color: yellow;
font-style: italic;
}
/* ii. Unordered lists in bold and Arial font */
ul {
font-weight: bold;
font-family: Arial, sans-serif;
}
/* iii. Background image with no tiling */
body {
background-image: url('birds.jpg');
background-repeat: no-repeat;
background-size: cover;
background-position: center;
}
</style>
</head>
<body>
<h1>Sample Web Page</h1>
<p>This is a paragraph with a <a href="https://example.com">hyperlink</a> that has yellow background and italic text.</p>
<h2>Skills:</h2>
<ul>
<li>HTML5</li>
<li>CSS3</li>
<li>JavaScript</li>
<li>PHP</li>
</ul>
<p>Visit our <a href="about.html">About Page</a> for more information.</p>
</body>
</html>
Explanation of CSS Properties:
-
Hyperlink Styling (
aselector):background-color: yellow;- Sets yellow background for linksfont-style: italic;- Makes link text italic
-
Unordered List Styling (
ulselector):font-weight: bold;- Makes list items boldfont-family: Arial, sans-serif;- Sets Arial font with sans-serif fallback
-
Background Image (applied to
body):background-image: url('birds.jpg');- Specifies the image filebackground-repeat: no-repeat;- Prevents tiling/repetition of imagebackground-size: cover;- Scales image to cover entire viewportbackground-position: center;- Centers the image
Mark Distribution for Question 13(a):
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 13(a) - MARK DISTRIBUTION (Total: 6 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Hyperlink Styling (yellow bg, italics) │ 2 marks │
│ - CSS selector for anchors (a) │ │
│ - background-color: yellow property │ │
│ - font-style: italic property │ │
│ │ │
│ 2. Unordered List Styling (bold, Arial) │ 2 marks │
│ - CSS selector for ul │ │
│ - font-weight: bold property │ │
│ - font-family: Arial property │ │
│ │ │
│ 3. Background Image (no tiling) │ 2 marks │
│ - background-image with URL │ │
│ - background-repeat: no-repeat │ │
│ - Additional properties (cover, center) │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Three Equal Parts (2+2+2)
Reference: Section 2.2, Pattern 2 from CST463_Marking_Scheme_Pattern_Analysis.md
b) List three methods for creating an array object in JavaScript. What function does the array methods join() and slice() perform? (8 marks)
Answer:
Three Methods for Creating Array Objects in JavaScript:
1. Array Literal Notation (Most Common)
// Simple array literal
let fruits = ["Apple", "Banana", "Orange"];
// Empty array
let emptyArray = [];
// Mixed data types
let mixedArray = [1, "Hello", true, null, {name: "John"}];
console.log(fruits); // Output: ["Apple", "Banana", "Orange"]
2. Array Constructor (using new Array())
// Create array with elements
let numbers = new Array(10, 20, 30, 40);
// Create empty array with specific length
let fixedLength = new Array(5); // Creates array with 5 empty slots
// Single element
let singleElement = new Array("Hello");
console.log(numbers); // Output: [10, 20, 30, 40]
console.log(fixedLength.length); // Output: 5
3. Array.of() Method
// Creates array from arguments
let arr1 = Array.of(7); // Creates [7]
let arr2 = Array.of(1, 2, 3); // Creates [1, 2, 3]
let arr3 = Array.of("a", "b", "c"); // Creates ["a", "b", "c"]
console.log(arr1); // Output: [7]
console.log(arr2); // Output: [1, 2, 3]
Array Methods: join() and slice()
1. join() Method
Purpose: Converts all elements of an array into a single string, with elements separated by a specified separator.
Syntax: array.join(separator)
Features:
- Returns a string (not an array)
- Default separator is comma (,)
- Does not modify original array
- Useful for creating formatted strings from array data
Examples:
let fruits = ["Apple", "Banana", "Orange", "Mango"];
// Default separator (comma)
let result1 = fruits.join();
console.log(result1); // Output: "Apple,Banana,Orange,Mango"
// Custom separator - space
let result2 = fruits.join(" ");
console.log(result2); // Output: "Apple Banana Orange Mango"
// Custom separator - hyphen
let result3 = fruits.join("-");
console.log(result3); // Output: "Apple-Banana-Orange-Mango"
// Custom separator - with spaces
let result4 = fruits.join(" | ");
console.log(result4); // Output: "Apple | Banana | Orange | Mango"
// Empty separator
let letters = ["H", "e", "l", "l", "o"];
let word = letters.join("");
console.log(word); // Output: "Hello"
2. slice() Method
Purpose: Extracts a section of an array and returns a new array without modifying the original array.
Syntax: array.slice(start, end)
Parameters:
- start: Index where extraction begins (inclusive)
- end: Index where extraction ends (exclusive) - optional
Features:
- Returns a new array (shallow copy)
- Original array remains unchanged
- Negative indices count from end of array
- If end is omitted, extracts till end of array
Examples:
let numbers = [10, 20, 30, 40, 50, 60, 70];
// Extract from index 2 to 5 (5 not included)
let slice1 = numbers.slice(2, 5);
console.log(slice1); // Output: [30, 40, 50]
// Extract from index 3 to end
let slice2 = numbers.slice(3);
console.log(slice2); // Output: [40, 50, 60, 70]
// Extract from beginning to index 4
let slice3 = numbers.slice(0, 4);
console.log(slice3); // Output: [10, 20, 30, 40]
// Using negative indices (from end)
let slice4 = numbers.slice(-3);
console.log(slice4); // Output: [50, 60, 70]
// Negative start and end
let slice5 = numbers.slice(-5, -2);
console.log(slice5); // Output: [30, 40, 50]
// Create a shallow copy of entire array
let copy = numbers.slice();
console.log(copy); // Output: [10, 20, 30, 40, 50, 60, 70]
// Original array unchanged
console.log(numbers); // Output: [10, 20, 30, 40, 50, 60, 70]
Practical Use Cases:
// Use case 1: Pagination
let allItems = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let page1 = allItems.slice(0, 3); // First 3 items
let page2 = allItems.slice(3, 6); // Next 3 items
// Use case 2: Removing first/last elements without modifying original
let data = ["header", "item1", "item2", "footer"];
let mainContent = data.slice(1, -1); // Output: ["item1", "item2"]
// Use case 3: Combining with join()
let words = ["JavaScript", "is", "awesome"];
let sentence = words.slice(0, 2).join(" "); // Output: "JavaScript is"
Key Differences Summary:
| Feature | join() | slice() |
|---|---|---|
| Return Type | String | Array |
| Purpose | Convert array to string | Extract portion of array |
| Parameters | Separator string | Start and end indices |
| Modifies Original | No | No |
| Common Use | Display formatting | Array manipulation |
Mark Distribution for Question 13(b):
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 13(b) - MARK DISTRIBUTION (Total: 8 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Three Array Creation Methods │ 6 marks │
│ a) Array Literal Notation │ 2 marks │
│ - Syntax and examples │ │
│ - Multiple use cases shown │ │
│ │ │
│ b) Array Constructor (new Array()) │ 2 marks │
│ - Syntax and examples │ │
│ - Different constructor patterns │ │
│ │ │
│ c) Array.of() Method │ 2 marks │
│ - Syntax and examples │ │
│ - Usage demonstration │ │
│ │ │
│ 2. Array Methods Explanation │ 2 marks │
│ a) join() method │ 1 mark │
│ - Purpose, syntax, features │ │
│ - Multiple examples with separators │ │
│ │ │
│ b) slice() method │ 1 mark │
│ - Purpose, syntax, parameters │ │
│ - Multiple examples with indices │ │
│ - Practical use cases │ │
│ - Comparison table │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Theory (6) + Methods Explanation (2)
Reference: Section 5.2 (JavaScript Questions) from
CST463_Marking_Scheme_Pattern_Analysis.md
Question 14 (14 marks)
a) Illustrate the usage of JavaScript DOM in event handling and explain any three methods with example. (8 marks)
Answer:
JavaScript DOM in Event Handling:
The Document Object Model (DOM) provides methods to handle user interactions (events) on web pages. Event handling allows JavaScript to respond to user actions like clicks, mouse movements, keyboard input, and form submissions.
Three Important DOM Event Handling Methods:
1. addEventListener() Method
Purpose: Attaches an event handler to an element without overwriting existing event handlers.
Syntax: element.addEventListener(event, function, useCapture)
Advantages:
- Can add multiple event listeners to same element
- Can be removed using
removeEventListener() - More flexible and modern approach
Example:
<!DOCTYPE html>
<html>
<head>
<title>addEventListener Example</title>
<style>
#myButton {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
margin: 10px;
}
.message {
color: blue;
font-weight: bold;
margin: 10px;
}
</style>
</head>
<body>
<h2>addEventListener() Method</h2>
<button id="myButton">Click Me</button>
<p id="demo"></p>
<script>
// Get element reference
let button = document.getElementById("myButton");
let demo = document.getElementById("demo");
// Add first event listener
button.addEventListener("click", function() {
demo.innerHTML = "Button was clicked!";
demo.className = "message";
});
// Add second event listener to same button
button.addEventListener("click", function() {
console.log("Second listener: Click event logged");
});
// Add mouseover event
button.addEventListener("mouseover", function() {
this.style.backgroundColor = "#45a049";
});
// Add mouseout event
button.addEventListener("mouseout", function() {
this.style.backgroundColor = "#4CAF50";
});
</script>
</body>
</html>
2. getElementById() Method
Purpose: Selects and returns a single HTML element by its unique id attribute, allowing manipulation and event handling.
Syntax: document.getElementById(elementId)
Example:
<!DOCTYPE html>
<html>
<head>
<title>getElementById Example</title>
<style>
.highlight {
background-color: yellow;
padding: 10px;
border: 2px solid orange;
}
input {
margin: 10px;
padding: 5px;
}
</style>
</head>
<body>
<h2>getElementById() for Event Handling</h2>
<input type="text" id="nameInput" placeholder="Enter your name">
<button id="submitBtn">Submit</button>
<p id="output"></p>
<script>
// Get elements by ID
let inputField = document.getElementById("nameInput");
let submitButton = document.getElementById("submitBtn");
let outputPara = document.getElementById("output");
// Handle button click event
submitButton.onclick = function() {
let userName = inputField.value;
if (userName === "") {
outputPara.innerHTML = "Please enter your name!";
outputPara.style.color = "red";
} else {
outputPara.innerHTML = "Welcome, " + userName + "!";
outputPara.style.color = "green";
outputPara.className = "highlight";
}
};
// Handle input field focus event
inputField.onfocus = function() {
this.style.backgroundColor = "#e7f3ff";
};
// Handle input field blur event
inputField.onblur = function() {
this.style.backgroundColor = "white";
};
// Handle keypress in input field
inputField.onkeypress = function(event) {
if (event.key === "Enter") {
submitButton.click();
}
};
</script>
</body>
</html>
3. querySelector() Method
Purpose: Returns the first element that matches a specified CSS selector. More flexible than getElementById() as it works with any CSS selector.
Syntax: document.querySelector(cssSelector)
Example:
<!DOCTYPE html>
<html>
<head>
<title>querySelector Example</title>
<style>
.box {
width: 200px;
height: 100px;
background-color: lightblue;
margin: 10px;
padding: 20px;
border: 2px solid blue;
cursor: pointer;
transition: all 0.3s;
}
.box:hover {
transform: scale(1.05);
}
.clicked {
background-color: coral;
border-color: red;
}
ul li {
margin: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<h2>querySelector() Method</h2>
<div class="box">Click this box</div>
<h3>Select a programming language:</h3>
<ul>
<li class="lang">JavaScript</li>
<li class="lang">Python</li>
<li class="lang">PHP</li>
<li class="lang">Java</li>
</ul>
<p id="selection"></p>
<script>
// Select first element with class "box"
let box = document.querySelector(".box");
// Add click event to box
box.addEventListener("click", function() {
this.classList.toggle("clicked");
this.innerHTML = this.classList.contains("clicked")
? "Box is clicked!"
: "Click this box";
});
// Select all elements with class "lang" using querySelectorAll
let languages = document.querySelectorAll(".lang");
let selectionPara = document.querySelector("#selection");
// Add event listeners to each language
languages.forEach(function(lang) {
lang.addEventListener("click", function() {
selectionPara.innerHTML = "You selected: " + this.textContent;
selectionPara.style.color = "green";
selectionPara.style.fontWeight = "bold";
// Remove highlight from all items
languages.forEach(l => l.style.backgroundColor = "");
// Highlight selected item
this.style.backgroundColor = "#ffeb3b";
});
});
// Select first paragraph and add double-click event
let firstPara = document.querySelector("p");
firstPara.addEventListener("dblclick", function() {
this.style.fontSize = "24px";
this.style.color = "purple";
});
</script>
</body>
</html>
Summary of DOM Event Handling Methods:
| Method | Purpose | Example Selector |
|---|---|---|
| addEventListener() | Attach event handlers | elem.addEventListener("click", fn) |
| getElementById() | Select element by ID | document.getElementById("myId") |
| querySelector() | Select element by CSS selector | document.querySelector(".class") |
Common Events:
- click: Mouse click on element
- dblclick: Double-click on element
- mouseover: Mouse pointer enters element
- mouseout: Mouse pointer leaves element
- keypress: Key is pressed
- focus: Element receives focus
- blur: Element loses focus
- submit: Form is submitted
Mark Distribution for Question 14(a):
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 14(a) - MARK DISTRIBUTION (Total: 8 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. DOM Usage in Event Handling (Concept) │ 2 marks │
│ - JavaScript DOM explanation │ │
│ - Event handling mechanism │ │
│ │ │
│ 2. Three DOM Methods (2 marks each) │ 6 marks │
│ a) addEventListener() method │ 2 marks │
│ - Purpose and syntax │ │
│ - Complete code example │ │
│ │ │
│ b) getElementById() method │ 2 marks │
│ - Purpose and syntax │ │
│ - Complete code example │ │
│ │ │
│ c) querySelector() method │ 2 marks │
│ - Purpose and syntax │ │
│ - Complete code example │ │
│ - Practical demonstration │ │
│ - Summary table and common events list │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: DOM Concept (2) + Three Methods (6)
Reference: Section 5.2 (JavaScript Questions) from
CST463_Marking_Scheme_Pattern_Analysis.md
b) List the order of precedence of style levels. Organize a sample web page for providing 'KTU B Tech Honours Regulation 19' for KTU and use embedded Style sheet to apply minimum 5 styles for list, tables and pages. (6 marks)
Answer:
Order of Precedence of Style Levels (Highest to Lowest):
-
Inline Styles (Highest Priority)
- Applied directly to HTML elements using
styleattribute - Example:
<p style="color: red;">
- Applied directly to HTML elements using
-
Internal/Embedded Styles
- Defined in
<style>tag within<head>section - Applies to entire document
- Defined in
-
External Styles
- Defined in separate CSS file linked using
<link>tag - Can be reused across multiple pages
- Defined in separate CSS file linked using
-
Browser Default Styles (Lowest Priority)
- Built-in default styles provided by web browser
Important Rules:
- !important declaration overrides all other styles
- More specific selectors have higher priority (CSS Specificity)
- Later rules override earlier rules (if same specificity)
Sample Web Page with Embedded Stylesheet:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>KTU B Tech Honours Regulation 19</title>
<style>
/* Style 1: Page-level styling */
body {
font-family: Arial, sans-serif;
background-color: #f0f8ff;
margin: 0;
padding: 20px;
line-height: 1.6;
}
/* Style 2: Heading styling */
h1 {
color: #2c3e50;
text-align: center;
background-color: #3498db;
color: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
h2 {
color: #e74c3c;
border-bottom: 2px solid #e74c3c;
padding-bottom: 10px;
}
/* Style 3: List styling */
ul {
background-color: #ecf0f1;
padding: 20px 40px;
border-left: 4px solid #3498db;
margin: 20px 0;
}
ul li {
margin: 10px 0;
font-weight: bold;
color: #34495e;
}
ol {
background-color: #ffeaa7;
padding: 20px 40px;
border-left: 4px solid #fdcb6e;
}
ol li {
margin: 8px 0;
color: #2d3436;
}
/* Style 4: Table styling */
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
table th {
background-color: #2980b9;
color: white;
padding: 12px;
text-align: left;
font-weight: bold;
}
table td {
padding: 10px;
border: 1px solid #ddd;
}
table tr:nth-child(even) {
background-color: #f2f2f2;
}
table tr:hover {
background-color: #e8f4f8;
}
/* Style 5: Container and section styling */
.container {
max-width: 1000px;
margin: 0 auto;
background-color: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 0 20px rgba(0,0,0,0.1);
}
.section {
margin: 30px 0;
padding: 20px;
background-color: #fafafa;
border-radius: 5px;
}
</style>
</head>
<body>
<div class="container">
<h1>KTU B.Tech Honours Regulation 19</h1>
<div class="section">
<h2>Programme Overview</h2>
<p>
The B.Tech Honours Programme under Regulation 19 is designed to provide
enhanced learning opportunities for academically excellent students at
APJ Abdul Kalam Technological University (KTU).
</p>
</div>
<div class="section">
<h2>Eligibility Criteria</h2>
<ul>
<li>CGPA of 8.0 or above at the end of Semester 4</li>
<li>No backlogs or failed courses</li>
<li>Good academic standing throughout</li>
<li>Completion of mandatory credits</li>
<li>Recommendation from department</li>
</ul>
</div>
<div class="section">
<h2>Programme Requirements</h2>
<ol>
<li>Complete 24 additional credits</li>
<li>Maintain minimum CGPA of 7.5</li>
<li>Complete honours project work</li>
<li>Publish/present research paper</li>
<li>Attend seminars and workshops</li>
</ol>
</div>
<div class="section">
<h2>Credit Distribution</h2>
<table>
<tr>
<th>Component</th>
<th>Credits</th>
<th>Semester</th>
<th>Remarks</th>
</tr>
<tr>
<td>Honours Course 1</td>
<td>3</td>
<td>5</td>
<td>Theory/Practical</td>
</tr>
<tr>
<td>Honours Course 2</td>
<td>3</td>
<td>6</td>
<td>Theory/Practical</td>
</tr>
<tr>
<td>Honours Course 3</td>
<td>3</td>
<td>7</td>
<td>Advanced Topics</td>
</tr>
<tr>
<td>Honours Project</td>
<td>9</td>
<td>7 & 8</td>
<td>Research Work</td>
</tr>
<tr>
<td>Honours Seminar</td>
<td>3</td>
<td>8</td>
<td>Presentation</td>
</tr>
<tr>
<td>Honours Viva</td>
<td>3</td>
<td>8</td>
<td>Final Assessment</td>
</tr>
</table>
</div>
<div class="section">
<h2>Key Benefits</h2>
<ul>
<li>Recognition of academic excellence</li>
<li>Enhanced career prospects</li>
<li>Research experience and exposure</li>
<li>Priority in placements and higher studies</li>
<li>Honours degree certificate</li>
</ul>
</div>
</div>
</body>
</html>
Explanation of Applied Styles:
- Page Styling: Background color, font family, padding, and responsive layout
- List Styling: Background colors, borders, padding, and font weights for
<ul>and<ol> - Table Styling: Border collapse, hover effects, alternating row colors, and header styling
- Typography: Heading colors, sizes, and text alignment
- Container Styling: Maximum width, shadows, border radius for professional appearance
CSS Specificity Applied:
- Element selectors (
body,h1,table) - Class selectors (
.container,.section) - Pseudo-classes (
:hover,:nth-child) - Combined selectors (
table th,ul li)
Mark Distribution for Question 14(b):
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 14(b) - MARK DISTRIBUTION (Total: 6 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Order of Precedence of Style Levels │ 2 marks │
│ - List of 4 levels (Inline, Embedded, │ │
│ External, Browser Default) │ │
│ - Explanation of each level │ │
│ │ │
│ 2. Sample Web Page with Embedded Stylesheet │ 4 marks │
│ - Complete HTML document structure │ │
│ - KTU B Tech Honours Regulation 19 content │ │
│ - Embedded <style> tag with minimum 5 │ │
│ styles applied to: │ │
│ * Lists styling │ │
│ * Tables styling │ │
│ * Page styling (body, headings, etc.) │ │
│ - Professional formatting │ │
│ - CSS specificity demonstration │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Concept (2) + Implementation (4)
Reference: Section 2.2, Pattern 1 from CST463_Marking_Scheme_Pattern_Analysis.md
MODULE III — ---
Question 15 (14 marks)
a) Write a PHP program to store the name and roll number of 10 students in an Associative Array and Use foreach loop to process the array and perform assort, rsort and ksort in the array. Illustrate with suitable output data. (6 marks)
Answer:
<?php
// Store name and roll number of 10 students in an Associative Array
$students = array(
"S101" => "John Doe",
"S105" => "Alice Smith",
"S103" => "Bob Johnson",
"S108" => "Carol Williams",
"S102" => "David Brown",
"S107" => "Emma Davis",
"S104" => "Frank Miller",
"S110" => "Grace Wilson",
"S106" => "Henry Moore",
"S109" => "Ivy Taylor"
);
echo "<h2>Original Array</h2>";
echo "<table border='1'>";
echo "<tr><th>Roll Number</th><th>Name</th></tr>";
foreach ($students as $roll => $name) {
echo "<tr><td>$roll</td><td>$name</td></tr>";
}
echo "</table><br>";
// 1. assort() - Sort array by values in ascending order (maintains key association)
$students_assort = $students;
asort($students_assort);
echo "<h2>After asort() - Sorted by Name (Ascending)</h2>";
echo "<table border='1'>";
echo "<tr><th>Roll Number</th><th>Name</th></tr>";
foreach ($students_assort as $roll => $name) {
echo "<tr><td>$roll</td><td>$name</td></tr>";
}
echo "</table><br>";
// 2. rsort() - Sort array by values in descending order (removes key association)
$students_rsort = $students;
rsort($students_rsort);
echo "<h2>After rsort() - Sorted by Name (Descending, Indexed)</h2>";
echo "<table border='1'>";
echo "<tr><th>Index</th><th>Name</th></tr>";
foreach ($students_rsort as $index => $name) {
echo "<tr><td>$index</td><td>$name</td></tr>";
}
echo "</table><br>";
// 3. ksort() - Sort array by keys in ascending order
$students_ksort = $students;
ksort($students_ksort);
echo "<h2>After ksort() - Sorted by Roll Number (Ascending)</h2>";
echo "<table border='1'>";
echo "<tr><th>Roll Number</th><th>Name</th></tr>";
foreach ($students_ksort as $roll => $name) {
echo "<tr><td>$roll</td><td>$name</td></tr>";
}
echo "</table><br>";
?>
Output Explanation:
Original Array:
| Roll Number | Name |
|------------|------|
| S101 | John Doe |
| S105 | Alice Smith |
| S103 | Bob Johnson |
| S108 | Carol Williams |
| S102 | David Brown |
| S107 | Emma Davis |
| S104 | Frank Miller |
| S110 | Grace Wilson |
| S106 | Henry Moore |
| S109 | Ivy Taylor |
After asort() - Sorted by Name (Ascending):
| Roll Number | Name |
|------------|------|
| S105 | Alice Smith |
| S103 | Bob Johnson |
| S108 | Carol Williams |
| S102 | David Brown |
| S107 | Emma Davis |
| S104 | Frank Miller |
| S110 | Grace Wilson |
| S106 | Henry Moore |
| S109 | Ivy Taylor |
| S101 | John Doe |
After rsort() - Sorted by Name (Descending):
| Index | Name |
|-------|------|
| 0 | John Doe |
| 1 | Ivy Taylor |
| 2 | Henry Moore |
| 3 | Grace Wilson |
| 4 | Frank Miller |
| 5 | Emma Davis |
| 6 | David Brown |
| 7 | Carol Williams |
| 8 | Bob Johnson |
| 9 | Alice Smith |
After ksort() - Sorted by Roll Number (Ascending):
| Roll Number | Name |
|------------|------|
| S101 | John Doe |
| S102 | David Brown |
| S103 | Bob Johnson |
| S104 | Frank Miller |
| S105 | Alice Smith |
| S106 | Henry Moore |
| S107 | Emma Davis |
| S108 | Carol Williams |
| S109 | Ivy Taylor |
| S110 | Grace Wilson |
Key Points:
- asort(): Sorts by values, maintains key-value association
- rsort(): Sorts by values in descending order, creates numeric indices (loses original keys)
- ksort(): Sorts by keys, maintains key-value association
- foreach loop: Efficiently iterates through associative arrays
Mark Distribution for Question 15(a):
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 15(a) - MARK DISTRIBUTION (Total: 6 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Associative Array Creation │ 1 mark │
│ - Array declaration with 10 students │ │
│ - Key-value pairs (roll_no => name) │ │
│ │ │
│ 2. foreach Loop Processing │ 1 mark │
│ - Iteration through array │ │
│ - Display of original array │ │
│ │ │
│ 3. Sorting Operations (1 mark each) │ 3 marks │
│ - asort() implementation and output │ 1 mark │
│ - rsort() implementation and output │ 1 mark │
│ - ksort() implementation and output │ 1 mark │
│ │ │
│ 4. Output Illustration │ 1 mark │
│ - Suitable test data │ │
│ - Clear demonstration of sorting effects │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Multiple Component Breakdown
Reference: Section 5.4 (PHP Questions) from CST463_Marking_Scheme_Pattern_Analysis.md
b) How does a PHP array differ from an array in C? 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:
Differences between PHP Array and C Array:
| Feature | PHP Array | C Array |
|---|---|---|
| Type | Dynamic, can hold mixed data types | Static, single data type only |
| Size | Dynamic, grows/shrinks automatically | Fixed size, declared at compile time |
| Index | Can use integers or strings (associative) | Integer indices only (0-based) |
| Memory | Automatically managed | Manually managed |
| Declaration | No size specification needed | Size must be declared: int arr[10] |
| Bounds Checking | No bounds checking (adds elements dynamically) | No automatic bounds checking (can overflow) |
| Multidimensional | Nested arrays with different sizes | Fixed dimensions |
| Built-in Functions | Rich set of array functions | Limited standard library support |
Different Ways to Create Arrays in PHP:
1. Using array() Function
// Indexed array
$fruits = array("Apple", "Banana", "Orange");
// Associative array
$student = array("name" => "John", "age" => 20, "course" => "B.Tech");
// Multidimensional array
$matrix = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
print_r($fruits);
2. Using Short Array Syntax (PHP 5.4+)
// Indexed array
$colors = ["Red", "Green", "Blue"];
// Associative array
$person = ["name" => "Alice", "age" => 25, "city" => "Mumbai"];
// Mixed array
$mixed = [1, "Hello", true, 3.14, ["nested", "array"]];
print_r($colors);
3. Using Direct Assignment
// Create empty array and add elements
$numbers = [];
$numbers[0] = 10;
$numbers[1] = 20;
$numbers[2] = 30;
// Associative array
$book["title"] = "Web Programming";
$book["author"] = "John Smith";
$book["year"] = 2024;
print_r($numbers);
4. Using range() Function
// Create array with range of numbers
$nums = range(1, 10); // [1, 2, 3, ..., 10]
// Range with step
$evens = range(0, 20, 2); // [0, 2, 4, ..., 20]
// Character range
$letters = range('A', 'E'); // ['A', 'B', 'C', 'D', 'E']
print_r($nums);
Four Important PHP Array Functions:
1. count() - Count Array Elements
Purpose: Returns the number of elements in an array.
Syntax: count($array, $mode)
Example:
$fruits = ["Apple", "Banana", "Orange", "Mango"];
$total = count($fruits);
echo "Total fruits: $total"; // Output: Total fruits: 4
// Multidimensional array
$data = [
[1, 2, 3],
[4, 5, 6],
[7, 8]
];
echo count($data); // Output: 3 (counts outer array)
echo count($data, COUNT_RECURSIVE); // Output: 11 (counts all elements recursively)
// Associative array
$student = ["name" => "John", "age" => 20, "grade" => "A"];
echo count($student); // Output: 3
2. array_push() - Add Elements to End
Purpose: Adds one or more elements to the end of an array.
Syntax: array_push($array, $value1, $value2, ...)
Example:
$stack = ["HTML", "CSS"];
echo "Original: ";
print_r($stack); // Output: ["HTML", "CSS"]
// Add single element
array_push($stack, "JavaScript");
print_r($stack); // Output: ["HTML", "CSS", "JavaScript"]
// Add multiple elements
array_push($stack, "PHP", "Python");
print_r($stack); // Output: ["HTML", "CSS", "JavaScript", "PHP", "Python"]
// Alternative syntax (faster for single element)
$stack[] = "Java";
print_r($stack); // Output: ["HTML", "CSS", "JavaScript", "PHP", "Python", "Java"]
3. array_merge() - Merge Arrays
Purpose: Merges one or more arrays into a single array.
Syntax: array_merge($array1, $array2, ...)
Example:
$array1 = ["a", "b", "c"];
$array2 = ["d", "e", "f"];
$array3 = ["g", "h"];
// Merge indexed arrays
$result = array_merge($array1, $array2, $array3);
print_r($result);
// Output: ["a", "b", "c", "d", "e", "f", "g", "h"]
// Merge associative arrays
$personal = ["name" => "John", "age" => 25];
$contact = ["email" => "john@example.com", "phone" => "1234567890"];
$combined = array_merge($personal, $contact);
print_r($combined);
// Output: ["name" => "John", "age" => 25, "email" => "john@example.com", "phone" => "1234567890"]
// Overlapping keys (later values override)
$arr1 = ["a" => "Apple", "b" => "Banana"];
$arr2 = ["b" => "Blueberry", "c" => "Cherry"];
$merged = array_merge($arr1, $arr2);
print_r($merged);
// Output: ["a" => "Apple", "b" => "Blueberry", "c" => "Cherry"]
4. in_array() - Check if Value Exists
Purpose: Checks if a specific value exists in an array.
Syntax: in_array($needle, $haystack, $strict)
Example:
$numbers = [10, 20, 30, 40, 50];
// Check if value exists
if (in_array(30, $numbers)) {
echo "30 exists in array"; // This will execute
} else {
echo "30 not found";
}
if (in_array(60, $numbers)) {
echo "60 exists";
} else {
echo "60 not found"; // This will execute
}
// Strict type checking (third parameter)
$mixed = [1, 2, "3", 4];
var_dump(in_array(3, $mixed)); // true (loose comparison)
var_dump(in_array(3, $mixed, true)); // false (strict comparison, "3" != 3)
var_dump(in_array("3", $mixed, true)); // true (exact match)
// With associative arrays
$student = ["name" => "Alice", "grade" => "A", "roll" => 101];
if (in_array("Alice", $student)) {
echo "Alice is a student"; // This will execute
}
// Search in multidimensional array
$users = [
["John", 25],
["Alice", 30],
["Bob", 28]
];
if (in_array(["Alice", 30], $users)) {
echo "User found"; // This will execute
}
Summary of Four Functions:
| Function | Purpose | Returns | Modifies Array |
|---|---|---|---|
| count() | Count elements | Integer | No |
| array_push() | Add to end | New count | Yes |
| array_merge() | Combine arrays | New array | No (creates new) |
| in_array() | Check existence | Boolean | No |
Mark Distribution for Question 15(b):
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 15(b) - MARK DISTRIBUTION (Total: 8 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. PHP Array vs C Array Differences │ 2 marks │
│ - Comparison table with 5+ aspects │ │
│ - Type, size, index, memory management │ │
│ │ │
│ 2. Ways to Create PHP Arrays with Examples │ 2 marks │
│ - At least 3 methods demonstrated │ │
│ - Code examples for each method │ │
│ │ │
│ 3. Four PHP Array Functions (1 mark each) │ 4 marks │
│ - count() with examples │ 1 mark │
│ - array_push() with examples │ 1 mark │
│ - array_merge() with examples │ 1 mark │
│ - in_array() with examples │ 1 mark │
│ - Summary table │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Multiple Components (2+2+4)
Reference: Section 5.4 (PHP Questions) from CST463_Marking_Scheme_Pattern_Analysis.md
Question 16 (14 marks)
a) Design an HTML form for entering a number by the user. Write a PHP code to display a message indicating, whether the number is odd or even, when clicking on the submit button. (6 marks)
Answer:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Odd or Even Checker</title>
</head>
<body>
<h2>Odd or Even Number Checker</h2>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<label for="number">Enter a number:</label>
<input type="number" id="number" name="number" required>
<button type="submit" name="submit">Check</button>
</form>
<?php
// Process form when submitted
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
// Get the number from form
$number = $_POST['number'];
// Check if number is odd or even
if ($number % 2 == 0) {
echo "<p style='color: green; font-weight: bold;'>";
echo "The number $number is EVEN";
echo "</p>";
} else {
echo "<p style='color: blue; font-weight: bold;'>";
echo "The number $number is ODD";
echo "</p>";
}
}
?>
</body>
</html>
Explanation:
-
HTML Form:
- Uses POST method for secure data transmission
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"submits to same page- Input type="number" ensures only numeric input
requiredattribute makes field mandatory
-
PHP Processing:
- Checks if form was submitted using
$_SERVER["REQUEST_METHOD"] == "POST" - Retrieves number using
$_POST['number'] - Uses modulo operator
%to check divisibility by 2 - If
$number % 2 == 0, number is even; otherwise, odd - Displays result with appropriate styling
- Checks if form was submitted using
-
Security:
htmlspecialchars()prevents XSS attacks- Form validation ensures data integrity
Test Cases:
- Input: 10 → Output: "The number 10 is EVEN"
- Input: 7 → Output: "The number 7 is ODD"
- Input: 0 → Output: "The number 0 is EVEN"
- Input: -5 → Output: "The number -5 is ODD"
Mark Distribution for Question 16(a):
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 16(a) - MARK DISTRIBUTION (Total: 6 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. HTML Form Design │ 3 marks │
│ - Form tag with action and method │ │
│ - Number input field with label │ │
│ - Submit button │ │
│ │ │
│ 2. PHP Odd/Even Logic │ 3 marks │
│ - $_POST data retrieval │ │
│ - Modulo operator (%) logic │ │
│ - Conditional check (if-else) │ │
│ - Output display with styling │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Two Major Parts (HTML + PHP Logic: 3+3)
Reference: Section 2.2, Pattern 1 from CST463_Marking_Scheme_Pattern_Analysis.md
b) Discuss various conditional and looping statements in PHP. (8 marks)
Answer:
CONDITIONAL STATEMENTS IN PHP
Conditional statements allow executing different code blocks based on specific conditions.
1. if Statement
Purpose: Executes code block if condition is true.
Syntax:
if (condition) {
// code to execute
}
Example:
$age = 20;
if ($age >= 18) {
echo "You are eligible to vote";
}
$temperature = 35;
if ($temperature > 30) {
echo "It's a hot day";
}
2. if-else Statement
Purpose: Executes one block if condition is true, another if false.
Syntax:
if (condition) {
// code if true
} else {
// code if false
}
Example:
$marks = 65;
if ($marks >= 50) {
echo "Pass";
} else {
echo "Fail";
}
$number = 15;
if ($number % 2 == 0) {
echo "$number is even";
} else {
echo "$number is odd";
}
3. if-elseif-else Statement
Purpose: Tests multiple conditions sequentially.
Syntax:
if (condition1) {
// code for condition1
} elseif (condition2) {
// code for condition2
} else {
// code if all false
}
Example:
$score = 75;
if ($score >= 90) {
echo "Grade: A+";
} elseif ($score >= 80) {
echo "Grade: A";
} elseif ($score >= 70) {
echo "Grade: B";
} elseif ($score >= 60) {
echo "Grade: C";
} elseif ($score >= 50) {
echo "Grade: D";
} else {
echo "Grade: F (Fail)";
}
// Output: Grade: B
4. switch Statement
Purpose: Tests a variable against multiple values (cleaner than multiple if-elseif).
Syntax:
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}
Example:
$day = 3;
switch ($day) {
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
case 3:
echo "Wednesday";
break;
case 4:
echo "Thursday";
break;
case 5:
echo "Friday";
break;
case 6:
echo "Saturday";
break;
case 7:
echo "Sunday";
break;
default:
echo "Invalid day";
}
// Output: Wednesday
LOOPING STATEMENTS IN PHP
Loops allow executing code repeatedly based on conditions.
1. while Loop
Purpose: Executes code while condition is true.
Syntax:
while (condition) {
// code to execute
}
Example:
// Print numbers 1 to 5
$i = 1;
while ($i <= 5) {
echo $i . " ";
$i++;
}
// Output: 1 2 3 4 5
// Calculate factorial
$num = 5;
$factorial = 1;
$counter = 1;
while ($counter <= $num) {
$factorial *= $counter;
$counter++;
}
echo "Factorial of $num is $factorial";
// Output: Factorial of 5 is 120
2. do-while Loop
Purpose: Executes code at least once, then repeats while condition is true.
Syntax:
do {
// code to execute
} while (condition);
Example:
// Execute at least once
$num = 10;
do {
echo "Number: $num<br>";
$num++;
} while ($num < 10);
// Output: Number: 10 (executes once even though condition is false)
// Menu-driven program example
$choice = 0;
do {
echo "1. Add\n";
echo "2. Subtract\n";
echo "3. Exit\n";
$choice = 3; // Simulated user input
} while ($choice != 3);
3. for Loop
Purpose: Executes code a specific number of times.
Syntax:
for (initialization; condition; increment) {
// code to execute
}
Example:
// Print numbers 1 to 10
for ($i = 1; $i <= 10; $i++) {
echo $i . " ";
}
// Output: 1 2 3 4 5 6 7 8 9 10
// Print multiplication table
$num = 7;
for ($i = 1; $i <= 10; $i++) {
echo "$num x $i = " . ($num * $i) . "<br>";
}
// Print even numbers
for ($i = 0; $i <= 20; $i += 2) {
echo $i . " ";
}
// Output: 0 2 4 6 8 10 12 14 16 18 20
// Nested for loop - pattern
for ($i = 1; $i <= 5; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo "* ";
}
echo "<br>";
}
// Output:
// *
// * *
// * * *
// * * * *
// * * * * *
4. foreach Loop
Purpose: Iterates through arrays.
Syntax:
// For indexed arrays
foreach ($array as $value) {
// use $value
}
// For associative arrays
foreach ($array as $key => $value) {
// use $key and $value
}
Example:
// Indexed array
$fruits = ["Apple", "Banana", "Orange", "Mango"];
foreach ($fruits as $fruit) {
echo "$fruit<br>";
}
// Output: Apple, Banana, Orange, Mango (each on new line)
// Associative array
$student = [
"name" => "John Doe",
"roll" => 101,
"course" => "B.Tech CSE",
"cgpa" => 8.5
];
foreach ($student as $key => $value) {
echo "$key: $value<br>";
}
// Output:
// name: John Doe
// roll: 101
// course: B.Tech CSE
// cgpa: 8.5
// Multidimensional array
$students = [
["John", 85],
["Alice", 92],
["Bob", 78]
];
foreach ($students as $student) {
echo "Name: {$student[0]}, Marks: {$student[1]}<br>";
}
Loop Control Statements:
1. break - Exits loop immediately
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break; // Exit loop when i equals 5
}
echo $i . " ";
}
// Output: 1 2 3 4
2. continue - Skips current iteration
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue; // Skip when i equals 3
}
echo $i . " ";
}
// Output: 1 2 4 5
Summary Table:
| Statement Type | Statement | Use Case |
|---|---|---|
| Conditional | if | Single condition |
| Conditional | if-else | Two alternatives |
| Conditional | if-elseif-else | Multiple conditions |
| Conditional | switch | Multiple values of same variable |
| Loop | while | Unknown iterations, condition-based |
| Loop | do-while | Execute at least once |
| Loop | for | Known number of iterations |
| Loop | foreach | Array iteration |
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 16(b) - MARK DISTRIBUTION (Total: 8 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. if Statement │ 1 mark │
│ - Purpose/Definition │ │
│ - Syntax structure │ │
│ - Practical example with output │ │
│ │ │
│ 2. if-else Statement │ 1 mark │
│ - Purpose/Definition │ │
│ - Syntax structure │ │
│ - Practical example with output │ │
│ │ │
│ 3. if-elseif-else Statement │ 1 mark │
│ - Purpose/Definition │ │
│ - Syntax structure │ │
│ - Practical example with output │ │
│ │ │
│ 4. switch Statement │ 1 mark │
│ - Purpose/Definition │ │
│ - Syntax structure │ │
│ - Practical example with output │ │
│ │ │
│ 5. while Loop │ 1 mark │
│ - Purpose/Definition │ │
│ - Syntax structure │ │
│ - Practical example with output │ │
│ │ │
│ 6. do-while Loop │ 1 mark │
│ - Purpose/Definition │ │
│ - Syntax structure │ │
│ - Practical example with output │ │
│ │ │
│ 7. for Loop │ 1 mark │
│ - Purpose/Definition │ │
│ - Syntax structure │ │
│ - Practical example with output │ │
│ │ │
│ 8. foreach Loop │ 1 mark │
│ - Purpose/Definition │ │
│ - Syntax structure │ │
│ - Practical example with output │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Multiple Statements (Equal Distribution)
Reference: Section 5.4 (PHP Questions) - 1 mark per statement type (8 types @ 1 mark each)
MODULE IV — ---
Question 17 (14 marks)
a) What is the significance of cookies in web? How can a cookie be created and destroyed in PHP? (6 marks)
Answer:
Significance of Cookies in Web:
Cookies are small pieces of data stored on the client's browser by the web server. They play a crucial role in web applications for maintaining state and personalizing user experience.
Key Significance:
-
Session Management:
- Maintain user login status across pages
- Store authentication tokens
- Track user sessions
-
Personalization:
- Remember user preferences (language, theme)
- Store customization settings
- Save shopping cart contents
-
Tracking and Analytics:
- Track user behavior and navigation patterns
- Collect statistics for website improvement
- Enable targeted advertising
-
State Preservation:
- HTTP is stateless; cookies maintain state
- Remember form data between requests
- Implement "Remember Me" functionality
-
User Experience Enhancement:
- Auto-fill forms with saved data
- Reduce login frequency
- Provide seamless navigation
Creating Cookies in PHP:
Syntax:
setcookie(name, value, expire, path, domain, secure, httponly);
Parameters:
- name: Cookie name (required)
- value: Cookie value
- expire: Expiration time (Unix timestamp)
- path: Path on server where cookie is available
- domain: Domain for which cookie is valid
- secure: Send only over HTTPS (true/false)
- httponly: Accessible only via HTTP (not JavaScript)
Examples:
<?php
// Example 1: Simple cookie (expires when browser closes)
setcookie("username", "John_Doe");
// Example 2: Cookie that expires in 1 hour
$expire_time = time() + 3600; // Current time + 3600 seconds (1 hour)
setcookie("user_id", "12345", $expire_time);
// Example 3: Cookie that expires in 30 days
$expire_time = time() + (30 * 24 * 60 * 60); // 30 days
setcookie("remember_me", "true", $expire_time, "/");
// Example 4: Secure cookie with multiple parameters
setcookie(
"session_token",
"abc123xyz789",
time() + 86400, // Expires in 1 day
"/", // Available throughout domain
"", // Domain (empty = current domain)
false, // Secure (HTTPS only)
true // HTTPOnly (not accessible via JavaScript)
);
// Example 5: Storing array values
setcookie("user[name]", "Alice");
setcookie("user[email]", "alice@example.com");
setcookie("user[role]", "admin");
// Accessing cookies
if (isset($_COOKIE["username"])) {
echo "Welcome back, " . $_COOKIE["username"];
} else {
echo "Welcome, new user!";
}
// Display all cookies
echo "<h3>All Cookies:</h3>";
foreach ($_COOKIE as $key => $value) {
echo "$key: $value<br>";
}
?>
Destroying/Deleting Cookies in PHP:
Method: Set the cookie's expiration time to a past timestamp
Syntax:
setcookie(name, "", time() - 3600, "/");
Examples:
<?php
// Example 1: Delete a specific cookie
setcookie("username", "", time() - 3600);
// Example 2: Delete cookie with explicit path
setcookie("user_id", "", time() - 3600, "/");
// Example 3: Delete all user data cookies
setcookie("user[name]", "", time() - 3600);
setcookie("user[email]", "", time() - 3600);
setcookie("user[role]", "", time() - 3600);
// Example 4: Complete cookie deletion with all parameters
setcookie(
"session_token",
"",
time() - 3600,
"/",
"",
false,
true
);
echo "Cookie deleted successfully";
?>
Complete Working Example:
<?php
// Create cookie
if (isset($_POST['create'])) {
setcookie("visitor_name", $_POST['name'], time() + 3600, "/");
echo "Cookie created! Refresh the page to see the cookie value.";
}
// Delete cookie
if (isset($_POST['delete'])) {
setcookie("visitor_name", "", time() - 3600, "/");
echo "Cookie deleted! Refresh the page to confirm.";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Cookie Demo</title>
</head>
<body>
<h2>Cookie Management</h2>
<?php
if (isset($_COOKIE["visitor_name"])) {
echo "<p>Current Cookie Value: <strong>" . $_COOKIE["visitor_name"] . "</strong></p>";
} else {
echo "<p>No cookie set</p>";
}
?>
<form method="POST">
<input type="text" name="name" placeholder="Enter your name" required>
<button type="submit" name="create">Create Cookie</button>
</form>
<form method="POST">
<button type="submit" name="delete">Delete Cookie</button>
</form>
</body>
</html>
Important Notes:
- setcookie() must be called before any HTML output
- Cookies are sent with HTTP headers
- Deleted cookies are removed on next page load
- Maximum cookie size: ~4KB
- Browsers limit number of cookies per domain
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 17(a) - MARK DISTRIBUTION (Total: 6 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Significance of Cookies │ 2 marks │
│ - Definition and purpose │ (0.5 mark) │
│ - Key significance points: │ (1.5 marks)│
│ • Session management │ │
│ • Personalization │ │
│ • Tracking and analytics │ │
│ • State preservation │ │
│ │ │
│ 2. Creating Cookies in PHP │ 2 marks │
│ - setcookie() syntax and parameters │ (1 mark) │
│ - Practical examples demonstrating │ (1 mark) │
│ cookie creation │ │
│ │ │
│ 3. Destroying Cookies in PHP │ 2 marks │
│ - Method/technique for deletion │ (1 mark) │
│ (setting expiration to past time) │ │
│ - Practical examples demonstrating │ (1 mark) │
│ cookie deletion │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Concept + Create + Destroy (Three Equal Parts @ 2 marks each)
Reference: Section 5.4 (PHP Questions), Section 2.2 (Pattern 2 - Three Equal Parts)
b) Write an embedded PHP script which displays the factorial of all numbers from 1 to 10 in a table in the web page. The factorial should be calculated and returned from a function. The table headings should be "Number" and "Factorial". (8 marks)
Answer:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Factorial Table</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 50px;
background-color: #f0f8ff;
}
h2 {
color: #2c3e50;
text-align: center;
}
table {
width: 50%;
margin: 30px auto;
border-collapse: collapse;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
th {
background-color: #3498db;
color: white;
padding: 12px;
font-size: 18px;
text-align: center;
}
td {
padding: 10px;
text-align: center;
border: 1px solid #ddd;
font-size: 16px;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
tr:hover {
background-color: #e8f4f8;
}
.number-col {
font-weight: bold;
color: #e74c3c;
}
.factorial-col {
color: #27ae60;
}
</style>
</head>
<body>
<h2>Factorial Table (1 to 10)</h2>
<?php
/**
* Calculate factorial of a number
* @param int $n The number to calculate factorial for
* @return int The factorial value
*/
function calculateFactorial($n) {
// Base cases
if ($n < 0) {
return -1; // Factorial not defined for negative numbers
}
if ($n == 0 || $n == 1) {
return 1;
}
// Calculate factorial using iteration
$factorial = 1;
for ($i = 2; $i <= $n; $i++) {
$factorial *= $i;
}
return $factorial;
}
// Alternative recursive implementation (commented)
/*
function calculateFactorialRecursive($n) {
if ($n <= 1) {
return 1;
}
return $n * calculateFactorialRecursive($n - 1);
}
*/
// Generate the factorial table
echo "<table>";
echo "<tr>";
echo "<th>Number</th>";
echo "<th>Factorial</th>";
echo "</tr>";
// Loop from 1 to 10 and display factorial for each number
for ($num = 1; $num <= 10; $num++) {
$factorial = calculateFactorial($num);
echo "<tr>";
echo "<td class='number-col'>$num</td>";
echo "<td class='factorial-col'>" . number_format($factorial) . "</td>";
echo "</tr>";
}
echo "</table>";
// Display additional information
echo "<div style='text-align: center; margin-top: 20px;'>";
echo "<p><strong>Formula:</strong> n! = n × (n-1) × (n-2) × ... × 2 × 1</p>";
echo "<p><strong>Example:</strong> 5! = 5 × 4 × 3 × 2 × 1 = 120</p>";
echo "</div>";
?>
</body>
</html>
Expected Output Table:
| Number | Factorial |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 6 |
| 4 | 24 |
| 5 | 120 |
| 6 | 720 |
| 7 | 5,040 |
| 8 | 40,320 |
| 9 | 362,880 |
| 10 | 3,628,800 |
Explanation:
-
calculateFactorial() Function:
- Takes an integer parameter
$n - Returns the factorial value
- Uses iterative approach with for loop
- Handles base cases (0 and 1)
- More efficient than recursive approach for this range
- Takes an integer parameter
-
Table Generation:
- Creates HTML table with professional styling
- Uses embedded CSS for better presentation
- Loops from 1 to 10 using for loop
- Calls
calculateFactorial()for each number - Uses
number_format()to display large numbers with comma separators
-
Features:
- Responsive design with centered table
- Hover effects for better user experience
- Alternating row colors for readability
- Color-coded columns (number in red, factorial in green)
- Additional information about factorial formula
Test Cases:
- Input: 1 → Output: 1
- Input: 5 → Output: 120
- Input: 10 → Output: 3,628,800
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 17(b) - MARK DISTRIBUTION (Total: 8 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Function Definition │ 3 marks │
│ - Proper function declaration with │ (0.5 mark) │
│ parameter │ │
│ - Correct factorial calculation logic │ (1.5 marks)│
│ with loop │ │
│ - Return statement with calculated value │ (0.5 mark) │
│ - Base case handling │ (0.5 mark) │
│ │ │
│ 2. Loop Logic (1 to 10) │ 2 marks │
│ - Correct for loop structure iterating │ (1 mark) │
│ from 1 to 10 │ │
│ - Proper function call within loop │ (1 mark) │
│ │ │
│ 3. HTML Table Structure │ 2 marks │
│ - Proper table tags with headers │ (1 mark) │
│ "Number" and "Factorial" │ │
│ - Correct table row and cell generation │ (1 mark) │
│ within loop │ │
│ │ │
│ 4. Output Display and Formatting │ 1 mark │
│ - Proper display of numbers and │ (0.5 mark) │
│ factorial values in table │ │
│ - Overall code organization and │ (0.5 mark) │
│ presentation │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Complete Program - Component-Based (Function + Loop + Table + Output)
Reference: Section 3.2 (Pattern 3 - Complete Program, 8 marks)
Question 18 (14 marks)
a) Write a PHP form handling program to perform the user registration of any website with a minimum of 5 different fields and delete the data from a MySQL table after establishing necessary connections with the Database. (8 marks)
Answer:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Registration and Management</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
}
.container {
max-width: 600px;
margin: 0 auto;
background-color: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 0 20px rgba(0,0,0,0.1);
}
h2 {
color: #333;
text-align: center;
margin-bottom: 30px;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
color: #555;
font-weight: bold;
}
input[type="text"],
input[type="email"],
input[type="password"],
input[type="number"],
select {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
box-sizing: border-box;
font-size: 14px;
}
button {
width: 100%;
padding: 12px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
margin-top: 10px;
}
button:hover {
background-color: #45a049;
}
.delete-btn {
background-color: #f44336;
}
.delete-btn:hover {
background-color: #da190b;
}
.message {
padding: 15px;
margin-bottom: 20px;
border-radius: 5px;
text-align: center;
}
.success {
background-color: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.error {
background-color: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
table {
width: 100%;
margin-top: 30px;
border-collapse: collapse;
}
table th {
background-color: #3498db;
color: white;
padding: 10px;
text-align: left;
}
table td {
padding: 8px;
border: 1px solid #ddd;
}
table tr:nth-child(even) {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<div class="container">
<h2>User Registration System</h2>
<?php
// Database connection using PDO
try {
$dsn = "mysql:host=localhost;dbname=user_registration;charset=utf8mb4";
$db_username = "root";
$db_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, $db_username, $db_password, $options);
// Create table if it doesn't exist
$create_table = "CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
email VARCHAR(100) NOT NULL,
password VARCHAR(255) NOT NULL,
phone VARCHAR(15),
age INT,
gender VARCHAR(10),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";
$pdo->exec($create_table);
// Handle Registration Form Submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['register'])) {
// Retrieve and sanitize form data
$username = trim($_POST['username']);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$password = $_POST['password'];
$phone = trim($_POST['phone']);
$age = (int)$_POST['age'];
$gender = $_POST['gender'];
// Validation
$errors = [];
if (empty($username) || strlen($username) < 3) {
$errors[] = "Username must be at least 3 characters";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format";
}
if (strlen($password) < 6) {
$errors[] = "Password must be at least 6 characters";
}
if ($age < 18 || $age > 100) {
$errors[] = "Age must be between 18 and 100";
}
if (empty($errors)) {
// Hash password for security
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// Prepared statement for INSERT
$sql = "INSERT INTO users (username, email, password, phone, age, gender)
VALUES (:username, :email, :password, :phone, :age, :gender)";
$stmt = $pdo->prepare($sql);
try {
$stmt->execute([
'username' => $username,
'email' => $email,
'password' => $hashed_password,
'phone' => $phone,
'age' => $age,
'gender' => $gender
]);
echo "<div class='message success'>Registration successful! User ID: " . $pdo->lastInsertId() . "</div>";
} catch (PDOException $e) {
if ($e->getCode() == 23000) {
echo "<div class='message error'>Username already exists!</div>";
} else {
echo "<div class='message error'>Registration failed: " . $e->getMessage() . "</div>";
}
}
} else {
echo "<div class='message error'>";
foreach ($errors as $error) {
echo $error . "<br>";
}
echo "</div>";
}
}
// Handle Delete Operation
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['delete'])) {
$delete_id = (int)$_POST['delete_id'];
if ($delete_id > 0) {
// Prepared statement for DELETE
$sql = "DELETE FROM users WHERE id = :id";
$stmt = $pdo->prepare($sql);
if ($stmt->execute(['id' => $delete_id])) {
if ($stmt->rowCount() > 0) {
echo "<div class='message success'>User with ID $delete_id deleted successfully!</div>";
} else {
echo "<div class='message error'>No user found with ID $delete_id</div>";
}
} else {
echo "<div class='message error'>Error deleting user</div>";
}
} else {
echo "<div class='message error'>Invalid user ID</div>";
}
}
} catch (PDOException $e) {
die("<div class='message error'>Database connection failed: " . $e->getMessage() . "</div>");
}
?>
<!-- Registration Form -->
<h3>Register New User</h3>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</div>
<div class="form-group">
<label for="phone">Phone Number:</label>
<input type="text" id="phone" name="phone" required>
</div>
<div class="form-group">
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="18" max="100" required>
</div>
<div class="form-group">
<label for="gender">Gender:</label>
<select id="gender" name="gender" required>
<option value="">Select Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>
</div>
<button type="submit" name="register">Register</button>
</form>
<!-- Delete User Form -->
<h3 style="margin-top: 40px;">Delete User</h3>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<div class="form-group">
<label for="delete_id">Enter User ID to Delete:</label>
<input type="number" id="delete_id" name="delete_id" min="1" required>
</div>
<button type="submit" name="delete" class="delete-btn" onclick="return confirm('Are you sure you want to delete this user?')">Delete User</button>
</form>
<!-- Display All Users -->
<h3 style="margin-top: 40px;">Registered Users</h3>
<?php
try {
$sql = "SELECT id, username, email, phone, age, gender, created_at FROM users ORDER BY id DESC";
$stmt = $pdo->query($sql);
$users = $stmt->fetchAll();
if (count($users) > 0) {
echo "<table>";
echo "<tr><th>ID</th><th>Username</th><th>Email</th><th>Phone</th><th>Age</th><th>Gender</th></tr>";
foreach ($users as $user) {
echo "<tr>";
echo "<td>" . htmlspecialchars($user['id']) . "</td>";
echo "<td>" . htmlspecialchars($user['username']) . "</td>";
echo "<td>" . htmlspecialchars($user['email']) . "</td>";
echo "<td>" . htmlspecialchars($user['phone']) . "</td>";
echo "<td>" . htmlspecialchars($user['age']) . "</td>";
echo "<td>" . htmlspecialchars($user['gender']) . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "<p style='text-align: center; color: #888;'>No users registered yet.</p>";
}
} catch (PDOException $e) {
echo "<div class='message error'>Error fetching users: " . $e->getMessage() . "</div>";
}
?>
</div>
</body>
</html>
Explanation:
1. Database Setup:
- PDO connection with proper error handling and security options
- Automatic table creation if it doesn't exist
- Table structure includes 7 fields: id, username, email, password, phone, age, gender
2. Registration Functionality:
- Collects 6 user input fields (username, email, password, phone, age, gender)
- Input validation for all fields
- Email format validation using
filter_var() - Password hashing using
password_hash()for security - Prepared statements prevent SQL injection
- Duplicate username check with proper error handling
3. Delete Functionality:
- Accepts user ID for deletion
- Uses prepared statements for security
- Confirms deletion with JavaScript prompt
- Displays success/error messages
- Checks if user exists before deletion
4. Security Features:
- PDO prepared statements with named parameters
- Password hashing (never store plain text passwords)
- Input sanitization with
trim()andfilter_var() - XSS prevention with
htmlspecialchars() - Form action points to same page securely
5. User Interface:
- Professional styling with CSS
- Responsive design
- Color-coded success/error messages
- Table display of all registered users
- Confirmation dialog for deletion
Test Cases:
- Register user: John/john@example.com/password123/9876543210/25/Male
- Delete user: Enter ID = 1
- View all users in table format
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 18(a) - MARK DISTRIBUTION (Total: 8 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. HTML Form Structure │ 2 marks │
│ - Proper HTML form with minimum 5 │ (1 mark) │
│ different input fields │ │
│ - Correct form attributes (method, action) │ (1 mark) │
│ and input types │ │
│ │ │
│ 2. PHP Form Processing │ 3 marks │
│ - Form data retrieval using $_POST │ (0.5 mark) │
│ - Data validation and sanitization │ (1 mark) │
│ - Registration logic and insert query │ (1 mark) │
│ execution │ │
│ - Delete functionality implementation │ (0.5 mark) │
│ │ │
│ 3. MySQL Database Operations │ 3 marks │
│ - Database connection establishment │ (1 mark) │
│ (mysqli_connect or PDO) │ │
│ - INSERT query for user registration │ (1 mark) │
│ with proper field binding │ │
│ - DELETE query with proper WHERE clause │ (1 mark) │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: HTML + PHP + MySQL Integration (Three-Component Distribution)
Reference: Section 5.6 (PHP-MySQL Questions), Distribution: HTML (2) + PHP (3) + MySQL (3)
b) Create a valid HTML document for yourself, including your name, address and email address. Also add your college, your major and the course. Perform form handling in PHP and process the output using POST method. (6 marks)
Answer:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Personal Information Form</title>
</head>
<body>
<h2>Personal Information Form</h2>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<label for="name">Full Name:</label><br>
<input type="text" id="name" name="name" required><br><br>
<label for="address">Address:</label><br>
<textarea id="address" name="address" rows="3" cols="50" required></textarea><br><br>
<label for="email">Email Address:</label><br>
<input type="email" id="email" name="email" required><br><br>
<label for="college">College Name:</label><br>
<input type="text" id="college" name="college" required><br><br>
<label for="major">Major/Department:</label><br>
<input type="text" id="major" name="major" required><br><br>
<label for="course">Course:</label><br>
<input type="text" id="course" name="course" required><br><br>
<button type="submit" name="submit">Submit</button>
</form>
<hr>
<?php
// Process form when submitted using POST method
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
// Retrieve form data
$name = htmlspecialchars(trim($_POST['name']));
$address = htmlspecialchars(trim($_POST['address']));
$email = htmlspecialchars(trim($_POST['email']));
$college = htmlspecialchars(trim($_POST['college']));
$major = htmlspecialchars(trim($_POST['major']));
$course = htmlspecialchars(trim($_POST['course']));
// Display processed output
echo "<h2>Submitted Information</h2>";
echo "<table border='1' cellpadding='10' cellspacing='0'>";
echo "<tr>";
echo "<th>Field</th>";
echo "<th>Value</th>";
echo "</tr>";
echo "<tr>";
echo "<td><strong>Full Name</strong></td>";
echo "<td>$name</td>";
echo "</tr>";
echo "<tr>";
echo "<td><strong>Address</strong></td>";
echo "<td>$address</td>";
echo "</tr>";
echo "<tr>";
echo "<td><strong>Email Address</strong></td>";
echo "<td>$email</td>";
echo "</tr>";
echo "<tr>";
echo "<td><strong>College Name</strong></td>";
echo "<td>$college</td>";
echo "</tr>";
echo "<tr>";
echo "<td><strong>Major/Department</strong></td>";
echo "<td>$major</td>";
echo "</tr>";
echo "<tr>";
echo "<td><strong>Course</strong></td>";
echo "<td>$course</td>";
echo "</tr>";
echo "</table>";
// Additional formatted output
echo "<h3>Profile Summary</h3>";
echo "<p>";
echo "Hello! My name is <strong>$name</strong>. I reside at <strong>$address</strong>. ";
echo "You can reach me at <strong>$email</strong>. ";
echo "I am currently pursuing <strong>$course</strong> with a major in <strong>$major</strong> ";
echo "at <strong>$college</strong>.";
echo "</p>";
}
?>
</body>
</html>
Explanation:
1. HTML Document Structure:
- Complete valid HTML5 document with DOCTYPE
- Includes
<html>,<head>, and<body>tags - Meta tags for character encoding and viewport
- Semantic form structure
2. Form Fields:
- Name: Text input for full name
- Address: Textarea for multi-line address
- Email: Email input with built-in validation
- College: Text input for college name
- Major: Text input for department/specialization
- Course: Text input for course name
3. PHP Form Processing:
- Checks for POST method submission
- Retrieves all form values using
$_POSTsuperglobal - Sanitizes input with
htmlspecialchars()andtrim() - Prevents XSS attacks
4. Output Display:
- Table format showing all submitted data
- Formatted profile summary paragraph
- Professional presentation of information
5. Security Features:
htmlspecialchars()prevents XSS attacks- Form action uses
$_SERVER["PHP_SELF"]securely - Input validation with required attributes
- Email format validation (HTML5)
Sample Test Data:
- Name: John Doe
- Address: 123 Main Street, Kochi, Kerala 682001
- Email: john.doe@student.edu
- College: APJ Abdul Kalam Technological University
- Major: Computer Science and Engineering
- Course: B.Tech CST463 - Web Programming
Output:
The form displays the submitted information in both table format and as a formatted profile summary paragraph.
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 18(b) - MARK DISTRIBUTION (Total: 6 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Valid HTML Document Structure │ 3 marks │
│ - Proper HTML5 document structure │ (0.5 mark) │
│ (DOCTYPE, html, head, body tags) │ │
│ - Form with all required personal │ (1 mark) │
│ information fields: name, address, email │ │
│ - Additional fields: college, major, course │ (1 mark) │
│ - Proper input types and labels │ (0.5 mark) │
│ │ │
│ 2. PHP Form Handling with POST Method │ 3 marks │
│ - Correct POST method implementation │ (0.5 mark) │
│ in form │ │
│ - PHP code to retrieve POST data using │ (1 mark) │
│ $_POST array │ │
│ - Processing and displaying the │ (1 mark) │
│ submitted data │ │
│ - Output formatting and presentation │ (0.5 mark) │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: HTML + PHP Integration (Two Equal Parts @ 3 marks each)
Reference: Section 2.2 (Pattern 1), Distribution: HTML document (3) + PHP form handling (3)
MODULE V — ---
Question 19 (14 marks)
a) With a neat diagram, explain about Laravel MVC Framework (6 marks)
Answer:
Laravel MVC Framework:
Laravel is a modern PHP web framework that follows the Model-View-Controller (MVC) architectural pattern. It provides an elegant syntax and powerful tools for building robust web applications.
MVC Architecture Diagram:
┌─────────────────────────────────────────────────────────────────┐
│ USER / BROWSER │
│ (Makes HTTP Request) │
└────────────────────────┬────────────────────────────────────────┘
│ HTTP Request
▼
┌─────────────────────────────────────────────────────────────────┐
│ ROUTES │
│ (routes/web.php) │
│ - Maps URLs to Controllers │
│ - Defines HTTP methods (GET, POST, PUT, DELETE) │
└────────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ CONTROLLER │
│ (app/Http/Controllers/) │
│ - Handles business logic │
│ - Receives user input │
│ - Interacts with Model │
│ - Returns View with data │
└───────┬─────────────────────────────────────────────┬───────────┘
│ │
│ Request Data │ Return View
▼ │
┌─────────────────────────────────┐ │
│ MODEL │ │
│ (app/Models/) │ │
│ - Represents database tables │ │
│ - Eloquent ORM │ │
│ - Business logic & validation │ │
│ - Database operations │ │
│ (CRUD operations) │ │
└───────┬─────────────────────────┘ │
│ │
│ Query │
▼ │
┌─────────────────────────────────┐ │
│ DATABASE │ │
│ (MySQL/PostgreSQL) │ │
│ - Stores data in tables │ │
│ - Handles data persistence │ │
└───────┬─────────────────────────┘ │
│ │
│ Data │
└─────────────────────────────────────────────┤
│
▼
┌─────────────────────────┐
│ VIEW │
│ (resources/views/) │
│ - Blade Templates │
│ - HTML + PHP │
│ - Displays data │
│ - User interface │
└────────┬────────────────┘
│
│ HTTP Response
▼
┌─────────────────────────┐
│ USER / BROWSER │
│ (Receives Response) │
└─────────────────────────┘
Components Explained:
1. Model (M)
Purpose: Represents data and business logic
Responsibilities:
- Interact with database using Eloquent ORM
- Define database table structure
- Perform CRUD operations (Create, Read, Update, Delete)
- Data validation and relationships
- Business logic implementation
Example:
// app/Models/Student.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $fillable = ['name', 'email', 'course', 'marks'];
// Relationships
public function courses()
{
return $this->hasMany(Course::class);
}
// Business logic
public function isPassed()
{
return $this->marks >= 50;
}
}
2. View (V)
Purpose: Presentation layer - displays data to user
Responsibilities:
- Render HTML content
- Use Blade templating engine
- Display data passed from Controller
- Handle user interface elements
- No business logic (separation of concerns)
Example:
<!-- resources/views/students/index.blade.php -->
<!DOCTYPE html>
<html>
<head>
<title>Student List</title>
</head>
<body>
<h1>All Students</h1>
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Course</th>
</tr>
@foreach($students as $student)
<tr>
<td>{{ $student->name }}</td>
<td>{{ $student->email }}</td>
<td>{{ $student->course }}</td>
</tr>
@endforeach
</table>
</body>
</html>
3. Controller (C)
Purpose: Intermediary between Model and View
Responsibilities:
- Handle HTTP requests
- Process user input
- Call Model methods to retrieve/manipulate data
- Pass data to Views
- Return HTTP responses
- Implement application logic
Example:
// app/Http/Controllers/StudentController.php
namespace App\Http\Controllers;
use App\Models\Student;
use Illuminate\Http\Request;
class StudentController extends Controller
{
public function index()
{
// Interact with Model
$students = Student::all();
// Pass data to View
return view('students.index', compact('students'));
}
public function store(Request $request)
{
// Validate and create new student
$validated = $request->validate([
'name' => 'required',
'email' => 'required|email',
'course' => 'required',
]);
Student::create($validated);
return redirect()->route('students.index');
}
}
Request-Response Flow:
- User Request: User accesses URL (e.g.,
/students) - Routing: Router maps URL to Controller method
- Controller: Processes request, interacts with Model
- Model: Queries database, returns data
- Controller: Receives data from Model
- View: Controller passes data to View
- Response: View renders HTML and sends to browser
Advantages of MVC in Laravel:
- Separation of Concerns: Each component has distinct responsibility
- Code Organization: Logical structure, easy to maintain
- Reusability: Models and Views can be reused
- Testability: Each component can be tested independently
- Scalability: Easy to scale and extend application
- Team Collaboration: Multiple developers can work simultaneously
Laravel-Specific Features:
- Eloquent ORM: Powerful database interaction
- Blade Templating: Clean, expressive view syntax
- Routing: Simple and expressive route definition
- Middleware: Request filtering and authentication
- Artisan CLI: Command-line tools for development
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 19(a) - MARK DISTRIBUTION (Total: 6 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Neat Diagram │ 2 marks │
│ - Clear MVC architecture diagram showing │ (1 mark) │
│ Model, View, Controller components │ │
│ - Proper flow arrows and relationships │ (1 mark) │
│ between components │ │
│ │ │
│ 2. MVC Explanation │ 4 marks │
│ - Model explanation: │ (1.5 marks)│
│ • Database interaction │ │
│ • Business logic │ │
│ • Data handling │ │
│ │ │
│ - View explanation: │ (1.5 marks)│
│ • Presentation layer │ │
│ • Blade templates │ │
│ • User interface │ │
│ │ │
│ - Controller explanation: │ (1 mark) │
│ • Request handling │ │
│ • Connects Model and View │ │
│ • Application logic │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Diagram + Explanation (Model 1.5 + View 1.5 + Controller 1)
Reference: Section 5.9 (Laravel Questions), Distribution: Diagram (2) + Explanation (4)
Note: Award full marks for complete diagram with all three MVC components clearly labeled and explanation covering roles and interactions of each component in Laravel context.
b) Explain how laravel performs route handling using routes calling controller methods? (8 marks)
Answer:
Laravel Route Handling:
Laravel's routing system provides a clean and expressive way to define application URLs and map them to controller methods or closures. Routes act as the entry point for all HTTP requests.
1. Basic Route Definition
Routes are defined in routes/web.php for web applications.
Syntax:
Route::HTTPmethod('URI', [ControllerClass::class, 'methodName']);
Example:
// routes/web.php
use App\Http\Controllers\StudentController;
// Basic GET route
Route::get('/students', [StudentController::class, 'index']);
// Basic POST route
Route::post('/students', [StudentController::class, 'store']);
// Route with parameter
Route::get('/students/{id}', [StudentController::class, 'show']);
// Route with multiple parameters
Route::get('/courses/{course}/students/{id}', [StudentController::class, 'showCourseStudent']);
2. HTTP Methods Supported
Laravel supports all standard HTTP methods:
Route::get($uri, $callback); // Retrieve data
Route::post($uri, $callback); // Create new resource
Route::put($uri, $callback); // Update entire resource
Route::patch($uri, $callback); // Update partial resource
Route::delete($uri, $callback); // Delete resource
Route::options($uri, $callback); // HTTP OPTIONS
// Match multiple methods
Route::match(['get', 'post'], '/form', [FormController::class, 'handle']);
// Match all HTTP methods
Route::any('/anything', [Controller::class, 'method']);
3. Route Parameters
Required Parameters:
Route::get('/user/{id}', [UserController::class, 'show']);
// Controller method
public function show($id)
{
$user = User::findOrFail($id);
return view('user.profile', ['user' => $user]);
}
Optional Parameters:
Route::get('/user/{name?}', [UserController::class, 'profile']);
// Controller method
public function profile($name = null)
{
return view('user.profile', ['name' => $name]);
}
Parameters with Constraints:
// Only numeric IDs
Route::get('/user/{id}', [UserController::class, 'show'])
->where('id', '[0-9]+');
// Only alphabetic names
Route::get('/user/{name}', [UserController::class, 'show'])
->where('name', '[A-Za-z]+');
// Multiple constraints
Route::get('/posts/{id}/{slug}', [PostController::class, 'show'])
->where(['id' => '[0-9]+', 'slug' => '[A-Za-z-]+']);
4. Named Routes
Named routes allow convenient URL generation and redirects.
// Define named route
Route::get('/student/profile', [StudentController::class, 'profile'])
->name('student.profile');
// Generate URL using route name
$url = route('student.profile');
// Redirect to named route
return redirect()->route('student.profile');
// Named route with parameters
Route::get('/student/{id}/edit', [StudentController::class, 'edit'])
->name('student.edit');
// Generate URL with parameters
$url = route('student.edit', ['id' => 1]);
// Output: /student/1/edit
5. Route Groups
Group routes to apply common attributes (middleware, prefixes, namespaces).
Middleware Groups:
Route::middleware(['auth'])->group(function () {
Route::get('/dashboard', [DashboardController::class, 'index']);
Route::get('/profile', [ProfileController::class, 'show']);
});
Prefix Groups:
Route::prefix('admin')->group(function () {
Route::get('/users', [AdminController::class, 'users']);
// URL: /admin/users
Route::get('/posts', [AdminController::class, 'posts']);
// URL: /admin/posts
});
Name Prefix Groups:
Route::name('admin.')->group(function () {
Route::get('/users', [AdminController::class, 'users'])
->name('users'); // Route name: admin.users
});
Combined Groups:
Route::middleware(['auth'])
->prefix('admin')
->name('admin.')
->group(function () {
Route::get('/dashboard', [AdminController::class, 'dashboard'])
->name('dashboard');
// URL: /admin/dashboard
// Route name: admin.dashboard
// Middleware: auth
});
6. Resource Routes
Laravel provides resource routing for CRUD operations.
Route::resource('students', StudentController::class);
This single line creates multiple routes:
| HTTP Method | URI | Controller Method | Route Name | Purpose |
|---|---|---|---|---|
| GET | /students | index | students.index | List all students |
| GET | /students/create | create | students.create | Show create form |
| POST | /students | store | students.store | Store new student |
| GET | /students/{id} | show | students.show | Show single student |
| GET | /students/{id}/edit | edit | students.edit | Show edit form |
| PUT/PATCH | /students/{id} | update | students.update | Update student |
| DELETE | /students/{id} | destroy | students.destroy | Delete student |
Partial Resource Routes:
// Only specific methods
Route::resource('photos', PhotoController::class)
->only(['index', 'show']);
// Exclude specific methods
Route::resource('photos', PhotoController::class)
->except(['create', 'store', 'update', 'destroy']);
7. Complete Example: Route to Controller Flow
Step 1: Define Routes
// routes/web.php
use App\Http\Controllers\StudentController;
Route::get('/students', [StudentController::class, 'index'])
->name('students.index');
Route::get('/students/create', [StudentController::class, 'create'])
->name('students.create');
Route::post('/students', [StudentController::class, 'store'])
->name('students.store');
Route::get('/students/{id}', [StudentController::class, 'show'])
->name('students.show')
->where('id', '[0-9]+');
Route::delete('/students/{id}', [StudentController::class, 'destroy'])
->name('students.destroy');
Step 2: Create Controller
// app/Http/Controllers/StudentController.php
namespace App\Http\Controllers;
use App\Models\Student;
use Illuminate\Http\Request;
class StudentController extends Controller
{
// Display list of all students
public function index()
{
$students = Student::all();
return view('students.index', compact('students'));
}
// Show form to create new student
public function create()
{
return view('students.create');
}
// Store new student in database
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|max:255',
'email' => 'required|email|unique:students',
'course' => 'required',
]);
Student::create($validated);
return redirect()->route('students.index')
->with('success', 'Student created successfully');
}
// Display specific student
public function show($id)
{
$student = Student::findOrFail($id);
return view('students.show', compact('student'));
}
// Delete student
public function destroy($id)
{
$student = Student::findOrFail($id);
$student->delete();
return redirect()->route('students.index')
->with('success', 'Student deleted successfully');
}
}
Step 3: Request Flow
- User visits:
http://example.com/students - Router matches:
Route::get('/students', ...) - Laravel calls:
StudentController@index - Controller executes: Retrieves all students from database
- Returns view:
students.indexwith student data - Browser receives: Rendered HTML page
8. Route Caching
For production, cache routes for better performance:
# Cache routes
php artisan route:cache
# Clear route cache
php artisan route:clear
9. Viewing All Routes
List all registered routes:
php artisan route:list
Output:
+--------+----------+-------------------+------------------+
| Method | URI | Name | Action |
+--------+----------+-------------------+------------------+
| GET | students | students.index | StudentController@index |
| POST | students | students.store | StudentController@store |
| GET | students/{id} | students.show | StudentController@show |
+--------+----------+-------------------+------------------+
Key Benefits of Laravel Routing:
- Clean URLs: RESTful and user-friendly URLs
- Organized Code: Separate routing logic from business logic
- Flexibility: Multiple ways to define routes
- Security: Built-in CSRF protection for POST requests
- Maintainability: Easy to update and manage routes
- Resource Routing: Quick CRUD implementation
- Middleware Support: Request filtering and authentication
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 19(b) - MARK DISTRIBUTION (Total: 8 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Route Handling Explanation │ 4 marks │
│ - Route definition in web.php/routes files │ (1 mark) │
│ - HTTP methods (GET, POST, PUT, DELETE) │ (1 mark) │
│ and route parameters │ │
│ - Route-to-Controller connection mechanism │ (1 mark) │
│ - Request flow from route to controller │ (1 mark) │
│ to response │ │
│ │ │
│ 2. Controller Methods Examples │ 4 marks │
│ - Basic route with controller method │ (1 mark) │
│ example │ │
│ - Route with parameters example │ (1 mark) │
│ - Resource routing example │ (1 mark) │
│ - Route naming and middleware application │ (1 mark) │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Explanation + Examples (Two Equal Parts @ 4 marks each)
Reference: Section 5.9 (Laravel Questions), Distribution: Explanation (4) + Examples (4)
Note: Award marks for clear explanation of Laravel's routing system including practical code examples demonstrating route definition, controller invocation, and parameter passing.
Question 20 (14 marks)
a) List the data types used in JSON? Illustrate the document definition of a 'Student document' using JSON Schema. (8 marks)
Answer:
Data Types in JSON:
JSON (JavaScript Object Notation) supports six fundamental data types:
1. String
- Text data enclosed in double quotes
- Examples:
"Hello World","John Doe","user@example.com"{ "name": "Alice", "email": "alice@example.com" }
2. Number
- Integer or floating-point values
- No quotes around numbers
- Examples:
42,3.14159,-10,1.5e10{ "age": 25, "marks": 85.5, "temperature": -5.2 }
3. Boolean
- Represents true or false values
- Only two values:
trueorfalse(lowercase){ "isStudent": true, "hasGraduated": false }
4. Null
- Represents empty or no value
- Written as:
null{ "middleName": null, "spouse": null }
5. Object
- Collection of key-value pairs enclosed in
{} - Keys must be strings
- Values can be any JSON data type
{ "person": { "name": "John", "age": 30, "address": { "city": "Mumbai", "pin": 400001 } } }
6. Array
- Ordered list of values enclosed in
[] - Can contain mixed data types
- Zero-indexed
{ "scores": [85, 92, 78, 95], "courses": ["Math", "Physics", "Chemistry"], "mixed": [1, "text", true, null, {"key": "value"}] }
Student Document using JSON Schema:
JSON Schema is a vocabulary that allows you to annotate and validate JSON documents.
Complete Student Document JSON Schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://example.com/student.schema.json",
"title": "Student",
"description": "A schema representing a student document",
"type": "object",
"properties": {
"studentId": {
"description": "Unique identifier for the student",
"type": "integer",
"minimum": 1
},
"name": {
"description": "Full name of the student",
"type": "string",
"minLength": 2,
"maxLength": 100
},
"email": {
"description": "Email address of the student",
"type": "string",
"format": "email"
},
"age": {
"description": "Age of the student in years",
"type": "integer",
"minimum": 18,
"maximum": 100
},
"dateOfBirth": {
"description": "Date of birth in YYYY-MM-DD format",
"type": "string",
"format": "date"
},
"gender": {
"description": "Gender of the student",
"type": "string",
"enum": ["Male", "Female", "Other"]
},
"address": {
"description": "Residential address",
"type": "object",
"properties": {
"street": {
"type": "string"
},
"city": {
"type": "string"
},
"state": {
"type": "string"
},
"pinCode": {
"type": "string",
"pattern": "^[0-9]{6}$"
},
"country": {
"type": "string",
"default": "India"
}
},
"required": ["city", "state", "pinCode"]
},
"courses": {
"description": "List of courses enrolled",
"type": "array",
"items": {
"type": "object",
"properties": {
"courseCode": {
"type": "string",
"pattern": "^[A-Z]{3}[0-9]{3}$"
},
"courseName": {
"type": "string"
},
"credits": {
"type": "integer",
"minimum": 1,
"maximum": 4
},
"grade": {
"type": "string",
"enum": ["A+", "A", "B+", "B", "C", "D", "F"]
}
},
"required": ["courseCode", "courseName", "credits"]
},
"minItems": 1
},
"marks": {
"description": "Total marks obtained",
"type": "number",
"minimum": 0,
"maximum": 100
},
"cgpa": {
"description": "Cumulative Grade Point Average",
"type": "number",
"minimum": 0.0,
"maximum": 10.0
},
"isActive": {
"description": "Whether the student is currently enrolled",
"type": "boolean",
"default": true
},
"scholarshipAmount": {
"description": "Scholarship amount (null if no scholarship)",
"type": ["number", "null"],
"minimum": 0
},
"skills": {
"description": "Technical skills of the student",
"type": "array",
"items": {
"type": "string"
},
"uniqueItems": true
},
"contactNumbers": {
"description": "Contact phone numbers",
"type": "array",
"items": {
"type": "string",
"pattern": "^[0-9]{10}$"
},
"minItems": 1,
"maxItems": 3
},
"enrollmentDate": {
"description": "Date of enrollment",
"type": "string",
"format": "date-time"
}
},
"required": [
"studentId",
"name",
"email",
"age",
"courses",
"isActive"
],
"additionalProperties": false
}
Valid Student Document Example:
{
"studentId": 12345,
"name": "Rahul Kumar",
"email": "rahul.kumar@university.edu",
"age": 21,
"dateOfBirth": "2003-05-15",
"gender": "Male",
"address": {
"street": "123 MG Road",
"city": "Kochi",
"state": "Kerala",
"pinCode": "682001",
"country": "India"
},
"courses": [
{
"courseCode": "CST463",
"courseName": "Web Programming",
"credits": 3,
"grade": "A"
},
{
"courseCode": "CST465",
"courseName": "Machine Learning",
"credits": 4,
"grade": "A+"
},
{
"courseCode": "CST461",
"courseName": "Compiler Design",
"credits": 3,
"grade": "B+"
}
],
"marks": 88.5,
"cgpa": 8.9,
"isActive": true,
"scholarshipAmount": 50000,
"skills": [
"HTML",
"CSS",
"JavaScript",
"PHP",
"Python",
"Laravel"
],
"contactNumbers": [
"9876543210",
"8765432109"
],
"enrollmentDate": "2021-08-15T10:00:00Z"
}
JSON Schema Keywords Explained:
| Keyword | Purpose | Example |
|---|---|---|
| $schema | Specifies JSON Schema version | "http://json-schema.org/draft-07/schema#" |
| title | Schema title/name | "Student" |
| description | Describes the schema/property | "A student document" |
| type | Data type | "string", "number", "object", "array" |
| properties | Defines object properties | Nested property definitions |
| required | Mandatory fields | ["studentId", "name", "email"] |
| minimum/maximum | Numeric constraints | "minimum": 0, "maximum": 100 |
| minLength/maxLength | String length constraints | "minLength": 2 |
| pattern | Regular expression validation | "pattern": "^[0-9]{10}$" |
| format | Built-in format validation | "format": "email", "format": "date" |
| enum | Allowed values | ["Male", "Female", "Other"] |
| items | Array item schema | Defines structure of array elements |
| minItems/maxItems | Array size constraints | "minItems": 1 |
| uniqueItems | Array uniqueness | "uniqueItems": true |
| default | Default value | "default": "India" |
| additionalProperties | Allow extra properties | false (strict) or true (flexible) |
Validation Example in PHP:
<?php
// Using justinrainbow/json-schema library
require 'vendor/autoload.php';
use JsonSchema\Validator;
// Student data
$studentData = json_decode('{
"studentId": 12345,
"name": "Rahul Kumar",
"email": "rahul@university.edu",
"age": 21,
"courses": [
{
"courseCode": "CST463",
"courseName": "Web Programming",
"credits": 3
}
],
"isActive": true
}');
// Load schema
$schema = json_decode(file_get_contents('student.schema.json'));
// Validate
$validator = new Validator();
$validator->validate($studentData, $schema);
if ($validator->isValid()) {
echo "Student document is valid!";
} else {
echo "Validation errors:\n";
foreach ($validator->getErrors() as $error) {
echo sprintf("[%s] %s\n", $error['property'], $error['message']);
}
}
?>
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 20(a) - MARK DISTRIBUTION (Total: 8 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. JSON Data Types │ 3 marks │
│ - List and explain 6 data types: │ (2 marks) │
│ String, Number, Boolean, Null, │ │
│ Object, Array │ │
│ - Provide examples for each data type │ (1 mark) │
│ │ │
│ 2. JSON Schema for Student Document │ 5 marks │
│ - Schema structure with $schema and │ (0.5 mark) │
│ $id declarations │ │
│ - Type definitions and properties │ (1.5 marks)│
│ - Required fields specification │ (1 mark) │
│ - Nested object/array definitions │ (1.5 marks)│
│ (courses, address, etc.) │ │
│ - Additional constraints (minLength, │ (0.5 mark) │
│ maxLength, format, pattern, etc.) │ │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Data Types + JSON Schema (3 + 5 marks distribution)
Reference: Section 5.8 (JSON Questions), Distribution: Data types (3) + JSON Schema (5)
Note: Award full marks for complete JSON Schema demonstrating proper structure, type validation, required fields, and realistic student properties with appropriate constraints.
b) Discuss the following in Laravel Views (6 marks)
- i. Creating and Rendering Views
- ii. Passing Data to Views
- iii. Sharing Data with All Views
Answer:
Laravel Views:
Views in Laravel contain the HTML served by your application and separate presentation logic from business logic. Views are stored in the resources/views directory and use the Blade templating engine.
i. Creating and Rendering Views
Creating Views:
Views are created as .blade.php files in the resources/views directory.
Directory Structure:
resources/
└── views/
├── welcome.blade.php
├── layouts/
│ └── app.blade.php
├── students/
│ ├── index.blade.php
│ ├── create.blade.php
│ └── show.blade.php
└── partials/
├── header.blade.php
└── footer.blade.php
Example View File:
<!-- resources/views/students/index.blade.php -->
<!DOCTYPE html>
<html>
<head>
<title>Students List</title>
</head>
<body>
<h1>All Students</h1>
<ul>
@foreach($students as $student)
<li>{{ $student->name }}</li>
@endforeach
</ul>
</body>
</html>
Rendering Views:
There are multiple ways to render views in Laravel:
1. Using view() Helper Function:
// In Controller
public function index()
{
return view('students.index');
}
// With subdirectories (dot notation)
return view('students.profile'); // resources/views/students/profile.blade.php
2. Using View Facade:
use Illuminate\Support\Facades\View;
return View::make('students.index');
3. Checking if View Exists:
if (View::exists('students.index')) {
return view('students.index');
}
4. Returning First Available View:
return view()->first(['students.custom', 'students.default']);
5. Determining View Path:
$viewPath = view()->getPath('students.index');
ii. Passing Data to Views
Laravel provides multiple methods to pass data from controllers to views.
Method 1: Array Parameter
public function show($id)
{
$student = Student::find($id);
return view('students.show', [
'student' => $student,
'title' => 'Student Profile'
]);
}
View Access:
<!-- resources/views/students/show.blade.php -->
<h1>{{ $title }}</h1>
<p>Name: {{ $student->name }}</p>
<p>Email: {{ $student->email }}</p>
Method 2: with() Method
public function show($id)
{
$student = Student::find($id);
return view('students.show')
->with('student', $student)
->with('title', 'Student Profile');
}
// Chain multiple with() calls
return view('students.show')
->with([
'student' => $student,
'title' => 'Student Profile'
]);
Method 3: compact() Function
public function show($id)
{
$student = Student::find($id);
$title = 'Student Profile';
$courses = Course::all();
return view('students.show', compact('student', 'title', 'courses'));
}
Method 4: Magic __set Method
public function index()
{
$view = view('students.index');
$view->students = Student::all();
$view->title = 'Students List';
return $view;
}
Complete Example:
Controller:
// app/Http/Controllers/StudentController.php
namespace App\Http\Controllers;
use App\Models\Student;
use Illuminate\Http\Request;
class StudentController extends Controller
{
public function index()
{
$students = Student::orderBy('name')->get();
$totalStudents = $students->count();
$title = 'All Students';
return view('students.index', compact('students', 'totalStudents', 'title'));
}
public function show($id)
{
$student = Student::with('courses')->findOrFail($id);
return view('students.show')
->with('student', $student)
->with('pageTitle', 'Student Details');
}
public function create()
{
$courses = Course::all();
return view('students.create', [
'courses' => $courses,
'formAction' => route('students.store')
]);
}
}
View:
<!-- resources/views/students/index.blade.php -->
<!DOCTYPE html>
<html>
<head>
<title>{{ $title }}</title>
</head>
<body>
<h1>{{ $title }}</h1>
<p>Total Students: {{ $totalStudents }}</p>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach($students as $student)
<tr>
<td>{{ $student->id }}</td>
<td>{{ $student->name }}</td>
<td>{{ $student->email }}</td>
<td>
<a href="{{ route('students.show', $student->id) }}">View</a>
</td>
</tr>
@endforeach
</tbody>
</table>
</body>
</html>
iii. Sharing Data with All Views
Sometimes you need to make data available to all views without passing it explicitly each time.
Method 1: Using View::share() in Service Provider
Best Practice: Add to AppServiceProvider
// app/Providers/AppServiceProvider.php
namespace App\Providers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
use App\Models\Setting;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
// Share single variable
View::share('appName', 'KTU University Portal');
// Share multiple variables
View::share('year', date('Y'));
View::share('copyright', 'KTU 2024');
// Share data from database
$settings = Setting::all();
View::share('siteSettings', $settings);
// Share computed value
$activeUsers = User::where('is_active', true)->count();
View::share('activeUsersCount', $activeUsers);
}
}
Access in Any View:
<!-- Any view file -->
<footer>
<p>{{ $appName }} © {{ $year }}</p>
<p>Active Users: {{ $activeUsersCount }}</p>
</footer>
Method 2: View Composers
View Composers are callbacks or class methods called when a view is rendered.
Create View Composer:
// app/Http/View/Composers/NavigationComposer.php
namespace App\Http\View\Composers;
use Illuminate\View\View;
use App\Models\Category;
class NavigationComposer
{
public function compose(View $view)
{
// Share categories with specific views
$categories = Category::orderBy('name')->get();
$view->with('categories', $categories);
}
}
Register View Composer:
// app/Providers/AppServiceProvider.php
use App\Http\View\Composers\NavigationComposer;
use Illuminate\Support\Facades\View;
public function boot()
{
// Attach to specific view
View::composer('layouts.navigation', NavigationComposer::class);
// Attach to multiple views
View::composer(['layouts.header', 'layouts.sidebar'], NavigationComposer::class);
// Attach to all views
View::composer('*', NavigationComposer::class);
// Using closure
View::composer('dashboard', function ($view) {
$view->with('stats', [
'users' => User::count(),
'posts' => Post::count()
]);
});
}
Method 3: Middleware
Share data using middleware for specific routes.
// app/Http/Middleware/ShareUserData.php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Auth;
class ShareUserData
{
public function handle($request, Closure $next)
{
if (Auth::check()) {
View::share('currentUser', Auth::user());
View::share('notifications', Auth::user()->notifications);
}
return $next($request);
}
}
Register Middleware:
// app/Http/Kernel.php
protected $middlewareGroups = [
'web' => [
// ... other middleware
\App\Http\Middleware\ShareUserData::class,
],
];
Complete Example:
Service Provider:
// app/Providers/ViewServiceProvider.php
namespace App\Providers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
use App\Models\Category;
use App\Models\Setting;
class ViewServiceProvider extends ServiceProvider
{
public function boot()
{
// Share with all views
View::share('siteName', config('app.name'));
View::share('currentYear', date('Y'));
// Share navigation categories with layout views
View::composer('layouts.app', function ($view) {
$categories = Category::with('subcategories')
->where('is_active', true)
->get();
$view->with('navCategories', $categories);
});
// Share user statistics with dashboard
View::composer('dashboard', function ($view) {
$view->with('stats', [
'totalUsers' => User::count(),
'activeUsers' => User::where('is_active', true)->count(),
'todayRegistrations' => User::whereDate('created_at', today())->count()
]);
});
}
}
Register Service Provider:
// config/app.php
'providers' => [
// Other providers...
App\Providers\ViewServiceProvider::class,
],
Usage in Views:
<!-- resources/views/layouts/app.blade.php -->
<!DOCTYPE html>
<html>
<head>
<title>{{ $siteName }}</title>
</head>
<body>
<nav>
@foreach($navCategories as $category)
<a href="{{ route('category.show', $category) }}">
{{ $category->name }}
</a>
@endforeach
</nav>
@yield('content')
<footer>
<p>© {{ $currentYear }} {{ $siteName }}</p>
</footer>
</body>
</html>
<!-- resources/views/dashboard.blade.php -->
@extends('layouts.app')
@section('content')
<h1>Dashboard</h1>
<div class="stats">
<div class="stat-card">
<h3>Total Users</h3>
<p>{{ $stats['totalUsers'] }}</p>
</div>
<div class="stat-card">
<h3>Active Users</h3>
<p>{{ $stats['activeUsers'] }}</p>
</div>
<div class="stat-card">
<h3>Today's Registrations</h3>
<p>{{ $stats['todayRegistrations'] }}</p>
</div>
</div>
@endsection
Summary:
| Method | Scope | Use Case |
|---|---|---|
| view() with data | Single view | Pass specific data to one view |
| View::share() | All views | Global data like app name, year |
| View Composers | Specific views | Data needed by multiple related views |
| Middleware | Route groups | User-specific data for authenticated routes |
Mark Distribution:
┌─────────────────────────────────────────────────────────────┐
│ QUESTION 20(b) - MARK DISTRIBUTION (Total: 6 marks) │
├─────────────────────────────────────────────────────────────┤
│ Component │ Marks │
├────────────────────────────────────────────────┼────────────┤
│ 1. Creating and Rendering Views │ 2 marks │
│ - View file location and naming convention │ (0.5 mark) │
│ (resources/views) │ │
│ - Creating view files with .blade.php │ (0.5 mark) │
│ extension │ │
│ - Rendering views using view() helper │ (0.5 mark) │
│ function │ │
│ - Return view from controller/routes │ (0.5 mark) │
│ │ │
│ 2. Passing Data to Views │ 2 marks │
│ - Using view() with array of data │ (0.5 mark) │
│ - Using with() method to pass data │ (0.5 mark) │
│ - Using compact() function │ (0.5 mark) │
│ - Accessing data in Blade templates │ (0.5 mark) │
│ │ │
│ 3. Sharing Data with All Views │ 2 marks │
│ - View::share() method in service provider │ (0.75 mark)│
│ - View Composers for specific views │ (0.75 mark)│
│ - Middleware approach for sharing data │ (0.5 mark) │
└────────────────────────────────────────────────┴────────────┘
Pattern Used: Three Topics @ 2 marks each (Creating + Passing + Sharing)
Reference: Section 2.2 (Pattern 2 - Three Equal Parts), Distribution: Creating (2) + Passing (2) + Sharing (2)
Note: Award marks for clear explanation with appropriate code examples demonstrating each Laravel Views concept.
End of Answer Key