CST463 Web Programming - Answer Key
CST463 Web Programming - Answer Key
November 2025 Examination
Subject: Web Programming (CST463)
Date: November 2025
Total Marks: 100
Duration: 3 Hours
University: APJ Abdul Kalam Technological University
Degree: B.Tech S7 (R,S) (FT/WP)
Scheme: 2019 Scheme
PART A (Short Answer Questions)
Instructions: Answer all questions, each carries 3 marks.
Question 1 (3 marks) β What is MIME? Discuss its importance in web communication.
What is MIME? Discuss its importance in web communication.
Answer:
MIME (Multipurpose Internet Mail Extensions) is a standard that extends the format of email messages and web content to support text in character sets other than ASCII, as well as attachments of audio, video, images, and application programs. In web communication, MIME types inform the browser about the nature of the content being transmitted, enabling proper rendering and handling of various file formats.
Key Points:
- MIME types use the format:
type/subtype(e.g.,text/html,image/jpeg) - Essential for HTTP communication - browsers use MIME types to determine how to display content
- Prevents security issues by explicitly defining content types
- Enables proper handling of multimedia content (audio, video, images)
Common MIME Type Examples:
text/html- HTML documentstext/css- CSS stylesheetsapplication/javascript- JavaScript filesimage/jpeg- JPEG imagesvideo/mp4- MP4 video filesapplication/json- JSON data
Importance in Web Communication:
- Content Identification: Web servers send MIME type in HTTP headers to inform browsers about content type
- Proper Rendering: Browsers use MIME types to decide whether to display, download, or execute content
- Security: Prevents browsers from misinterpreting malicious files
- Interoperability: Ensures consistent content handling across different platforms and browsers
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 1 - MARK DISTRIBUTION (Total: 3 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. MIME Definition & Concept Explanation β 1.5 marks β
β - Definition of MIME β β
β - Format (type/subtype) β β
β - Key points and examples β β
β β β
β 2. Importance in Web Communication β 1.5 marks β
β - Content identification β β
β - Proper rendering β β
β - Security aspects β β
β - Interoperability β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
Question 2 (3 marks) β Write the HTML code to embed a promotional video 'MyVideo.mp4' in a web page where 'autoplay' option is enabled and displayed in a standard dimension ...
Write the HTML code to embed a promotional video 'MyVideo.mp4' in a web page where 'autoplay' option is enabled and displayed in a standard dimension 750 X500.
Answer:
<video src="MyVideo.mp4" width="750" height="500" controls autoplay>
Your browser does not support the video tag.
</video>
Explanation:
<video>- HTML5 element for embedding video contentsrc="MyVideo.mp4"- Specifies the video file pathwidth="750" height="500"- Sets standard dimension as requiredcontrols- Displays playback controls (play, pause, volume, etc.)autoplay- Automatically starts playing when page loads- Fallback text appears if browser doesn't support video tag
Alternative with multiple source formats:
<video width="750" height="500" controls autoplay>
<source src="MyVideo.mp4" type="video/mp4">
<source src="MyVideo.webm" type="video/webm">
Your browser does not support the video tag.
</video>
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 2 - MARK DISTRIBUTION (Total: 3 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β Complete HTML Video Code β 3 marks β
β - <video> tag with proper syntax β β
β - width="750" and height="500" attributes β β
β - autoplay attribute enabled β β
β - src="MyVideo.mp4" specification β β
β - Fallback text for unsupported browsers β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
Question 3 (3 marks) β How are conflicts resolved when multiple style rules apply to a single web page element? External style sheets are usually preferred over other kinds ...
How are conflicts resolved when multiple style rules apply to a single web page element? External style sheets are usually preferred over other kinds of style sheets. Why?
Answer:
CSS Cascade and Specificity Resolution:
When multiple CSS rules apply to the same element, conflicts are resolved using the CSS cascade algorithm based on:
-
Specificity: Rules with higher specificity override lower specificity
- Inline styles (highest):
style="color: red;"- Specificity: 1,0,0,0 - ID selectors:
#header- Specificity: 0,1,0,0 - Class/attribute selectors:
.menu,[type="text"]- Specificity: 0,0,1,0 - Element selectors:
div,p- Specificity: 0,0,0,1
- Inline styles (highest):
-
Source Order: When specificity is equal, the last rule defined wins
-
Importance:
!importantdeclaration overrides normal rules (use sparingly) -
CSS Origin Priority (from lowest to highest):
- Browser default styles
- External stylesheets
- Internal stylesheets (embedded in
<style>tag) - Inline styles
Why External Stylesheets are Preferred:
- Separation of Concerns: Keeps content (HTML) separate from presentation (CSS)
- Reusability: Single CSS file can style multiple HTML pages
- Maintainability: Easier to update styles across entire website
- Caching: Browser can cache external CSS files, improving performance
- Collaboration: Different team members can work on HTML and CSS separately
- Cleaner HTML: Reduces code clutter in HTML documents
- Consistency: Ensures uniform styling across all web pages
Example:
<link rel="stylesheet" href="styles.css"> <!-- External - Preferred -->
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 3 - MARK DISTRIBUTION (Total: 3 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. CSS Conflict Resolution Mechanism β 1.5 marks β
β - Specificity rules and hierarchy β β
β - Source order β β
β - Importance (!important) β β
β - CSS origin priority β β
β β β
β 2. Why External Stylesheets are Preferred β 1.5 marks β
β - Separation of concerns β β
β - Reusability and maintainability β β
β - Caching and performance β β
β - Cleaner code and consistency β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
Question 4 (3 marks) β List any three data types in JavaScript and provide an example for each.
List any three data types in JavaScript and provide an example for each.
Answer:
JavaScript has several primitive and non-primitive data types. Here are three important ones:
1. String:
- Represents textual data enclosed in quotes (single, double, or backticks)
- Example:
let name = "John Doe";
let greeting = 'Hello World';
let template = `Welcome ${name}`; // Template literal
2. Number:
- Represents both integer and floating-point numbers
- Example:
let age = 25; // Integer
let price = 99.99; // Floating-point
let negative = -10; // Negative number
let scientific = 2.5e6; // Scientific notation (2500000)
3. Boolean:
- Represents logical values:
trueorfalse - Example:
let isStudent = true;
let isGraduated = false;
let hasAccess = (age >= 18); // Expression evaluates to boolean
Additional Common Data Types:
4. Object:
let person = {
name: "Alice",
age: 30,
city: "New York"
};
5. Array:
let colors = ["red", "green", "blue"];
let numbers = [1, 2, 3, 4, 5];
6. Undefined:
let x; // Declared but not assigned
console.log(x); // Output: undefined
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 4 - MARK DISTRIBUTION (Total: 3 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. String Data Type with Example β 1 mark β
β - Definition and explanation β β
β - Working code example β β
β β β
β 2. Number Data Type with Example β 1 mark β
β - Definition and explanation β β
β - Working code example β β
β β β
β 3. Boolean Data Type with Example β 1 mark β
β - Definition and explanation β β
β - Working code example β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
Question 5 (3 marks) β Explain any three string handling functions used in PHP.
Explain any three string handling functions used in PHP.
Answer:
PHP provides numerous built-in functions for string manipulation. Here are three commonly used string handling functions:
1. strlen() - String Length
- Returns the length of a string (number of characters)
- Syntax:
strlen(string $string): int - Example:
<?php
$text = "Hello World";
echo strlen($text); // Output: 11
?>
2. substr() - Extract Substring
- Extracts a portion of a string
- Syntax:
substr(string $string, int $start, int $length = null): string - Example:
<?php
$text = "Welcome to PHP";
echo substr($text, 0, 7); // Output: Welcome
echo substr($text, 11); // Output: PHP
echo substr($text, -3); // Output: PHP (from end)
?>
3. str_replace() - Search and Replace
- Replaces all occurrences of a search string with replacement string
- Syntax:
str_replace(mixed $search, mixed $replace, mixed $subject): string - Example:
<?php
$text = "I love JavaScript";
$newText = str_replace("JavaScript", "PHP", $text);
echo $newText; // Output: I love PHP
?>
Additional Useful Functions:
4. strtolower() and strtoupper():
<?php
echo strtolower("HELLO"); // Output: hello
echo strtoupper("world"); // Output: WORLD
?>
5. trim():
<?php
$text = " Hello World ";
echo trim($text); // Output: Hello World (removes whitespace)
?>
6. strpos() - Find Position:
<?php
$text = "Hello World";
echo strpos($text, "World"); // Output: 6 (position index)
?>
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 5 - MARK DISTRIBUTION (Total: 3 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. strlen() Function β 1 mark β
β - Purpose and explanation β β
β - Syntax β β
β - Working code example β β
β β β
β 2. substr() Function β 1 mark β
β - Purpose and explanation β β
β - Syntax β β
β - Working code examples β β
β β β
β 3. str_replace() Function β 1 mark β
β - Purpose and explanation β β
β - Syntax β β
β - Working code example β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
Question 6 (3 marks) β Write a PHP program to compute the sum of the positive integers up to 100 using a do while loop.
Write a PHP program to compute the sum of the positive integers up to 100 using a do while loop.
Answer:
<?php
// Compute sum of positive integers up to 100 using do-while loop
$sum = 0;
$i = 1;
do {
$sum += $i; // Add current number to sum
$i++; // Increment counter
} while ($i <= 100);
echo "Sum of positive integers from 1 to 100 is: $sum";
// Output: Sum of positive integers from 1 to 100 is: 5050
?>
Explanation:
- Initialize
$sum = 0to store the cumulative sum - Initialize counter
$i = 1to start from first positive integer do-whileloop executes at least once, then checks condition- In each iteration, add current value of
$ito$sum - Increment
$iby 1 after each addition - Loop continues while
$i <= 100 - Formula verification: Sum = n(n+1)/2 = 100(101)/2 = 5050
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 6 - MARK DISTRIBUTION (Total: 3 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β Complete PHP Program with do-while Loop β 3 marks β
β - Variable initialization ($sum, $i) β β
β - do-while loop structure β β
β - Loop logic (sum calculation) β β
β - Loop condition ($i <= 100) β β
β - Output display β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
Question 7 (3 marks) β Distinguish between implode and explode functions in PHP.
Distinguish between implode and explode functions in PHP.
Answer:
implode() and explode() are complementary string manipulation functions in PHP:
explode() Function:
- Purpose: Splits a string into an array based on a delimiter
- Syntax:
explode(string $separator, string $string, int $limit = PHP_INT_MAX): array - Returns: Array of strings
- Use case: Converting comma-separated values to array
Example:
<?php
$text = "apple,banana,orange,mango";
$fruits = explode(",", $text);
print_r($fruits);
// Output: Array ( [0] => apple [1] => banana [2] => orange [3] => mango )
?>
implode() Function:
- Purpose: Joins array elements into a single string with a separator
- Syntax:
implode(string $separator, array $array): string - Returns: String
- Use case: Converting array to comma-separated string
- Alias:
join()is an alias for implode()
Example:
<?php
$fruits = array("apple", "banana", "orange", "mango");
$text = implode(", ", $fruits);
echo $text;
// Output: apple, banana, orange, mango
?>
Key Differences:
| Aspect | explode() | implode() |
|---|---|---|
| Operation | String β Array | Array β String |
| Input | String with delimiter | Array of elements |
| Output | Array | String |
| Direction | Splits/Breaks apart | Joins/Combines |
| Parameters | (separator, string) | (separator, array) |
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 7 - MARK DISTRIBUTION (Total: 3 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. explode() Function β 1.5 marks β
β - Purpose and functionality β β
β - Syntax and parameters β β
β - Working code example β β
β β β
β 2. implode() Function β 1.5 marks β
β - Purpose and functionality β β
β - Syntax and parameters β β
β - Working code example β β
β - Key differences table β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
Question 8 (3 marks) β Write PHP statements to insert data into the MySQL table.
Write PHP statements to insert data into the MySQL table.
Answer:
Using PDO (PHP Data Objects) with Prepared Statements:
<?php
try {
// PDO Database connection
$dsn = "mysql:host=localhost;dbname=student_db;charset=utf8mb4";
$username = "root";
$password = "";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
$pdo = new PDO($dsn, $username, $password, $options);
// Prepare SQL statement with named parameters
$sql = "INSERT INTO students (name, email, age, course)
VALUES (:name, :email, :age, :course)";
$stmt = $pdo->prepare($sql);
// Execute with data array
$stmt->execute([
'name' => 'John Doe',
'email' => 'john@example.com',
'age' => 20,
'course' => 'Computer Science'
]);
echo "Record inserted successfully! ID: " . $pdo->lastInsertId();
} catch (PDOException $e) {
die("Error: " . $e->getMessage());
}
?>
Key Points:
- PDO provides database-independent interface
- Prepared statements prevent SQL injection attacks
- Named parameters (
:name,:email) improve code readability - Exception handling catches database errors
lastInsertId()returns the auto-increment ID of inserted record
Alternative using positional parameters:
<?php
$sql = "INSERT INTO students (name, email, age) VALUES (?, ?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute(['Alice Smith', 'alice@example.com', 22]);
?>
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 8 - MARK DISTRIBUTION (Total: 3 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. Connect to the MySQL Database β 1 mark β
β - PDO connection setup β β
β - Connection parameters (DSN, credentials) β β
β β β
β 2. Prepare the SQL INSERT Query β 1 mark β
β - INSERT statement syntax β β
β - Prepared statement with placeholders β β
β β β
β 3. Execute the Query to Insert Data β 1 mark β
β - Execute method with data β β
β - Error handling β β
β - Success confirmation β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
Question 9 (3 marks) β What is a Controller in Laravel, and how do you create and use it to handle HTTP requests?
What is a Controller in Laravel, and how do you create and use it to handle HTTP requests?
Answer:
Controller in Laravel:
A Controller is a PHP class that handles the application logic and acts as an intermediary between Models and Views in the MVC (Model-View-Controller) architecture. Controllers process incoming HTTP requests, interact with models to retrieve/manipulate data, and return appropriate responses (views or JSON).
Key Characteristics:
- Organizes request handling logic into reusable classes
- Located in
app/Http/Controllersdirectory - Each method represents an action (e.g., index, store, show, update, delete)
- Promotes separation of concerns and code organization
Creating a Controller:
1. Using Artisan Command:
# Create basic controller
php artisan make:controller StudentController
# Create resource controller with CRUD methods
php artisan make:controller StudentController --resource
2. Controller Structure:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class StudentController extends Controller
{
// Display all students
public function index()
{
$students = Student::all();
return view('students.index', compact('students'));
}
// Store new student
public function store(Request $request)
{
$student = Student::create($request->all());
return redirect()->route('students.index');
}
}
?>
3. Defining Routes:
// routes/web.php
use App\Http\Controllers\StudentController;
Route::get('/students', [StudentController::class, 'index']);
Route::post('/students', [StudentController::class, 'store']);
// Or use resource route for all CRUD operations
Route::resource('students', StudentController::class);
How it Handles HTTP Requests:
- User sends HTTP request (e.g., GET /students)
- Laravel router matches URL to controller method
- Controller method executes business logic
- Controller returns response (view, JSON, redirect)
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 9 - MARK DISTRIBUTION (Total: 3 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. Controller Definition & Concept β 1 mark β
β - What is a Controller β β
β - Role in MVC architecture β β
β - Key characteristics β β
β β β
β 2. Creating Controllers β 1 mark β
β - Artisan command syntax β β
β - Controller class structure β β
β - Method implementation β β
β β β
β 3. Using Controllers to Handle HTTP Requests β 1 mark β
β - Route definition β β
β - Request flow explanation β β
β - Response handling β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
Question 10 (3 marks) β Describe the JSON Object with suitable examples.
Describe the JSON Object with suitable examples.
Answer:
JSON (JavaScript Object Notation):
JSON is a lightweight, text-based data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is language-independent but uses conventions familiar to programmers of C-family languages including JavaScript, Python, PHP, and many others.
Key Characteristics:
- Data is represented in key-value pairs
- Uses curly braces
{}for objects and square brackets[]for arrays - Keys must be strings enclosed in double quotes
- Values can be: string, number, boolean, null, object, or array
- File extension:
.json - MIME type:
application/json
JSON Object Structure:
1. Simple JSON Object:
{
"name": "John Doe",
"age": 25,
"email": "john@example.com",
"isStudent": true,
"grade": null
}
2. Nested JSON Object:
{
"student": {
"id": 101,
"name": "Alice Smith",
"contact": {
"email": "alice@example.com",
"phone": "9876543210"
}
}
}
3. JSON Array:
{
"students": [
{
"id": 1,
"name": "John",
"marks": 85
},
{
"id": 2,
"name": "Mary",
"marks": 92
}
]
}
4. Complex JSON Example:
{
"course": "Web Programming",
"code": "CST463",
"credits": 3,
"modules": ["HTML5", "CSS3", "JavaScript", "PHP", "Laravel"],
"instructor": {
"name": "Dr. Smith",
"department": "Computer Science"
},
"enrolled": 45,
"isActive": true
}
JSON Data Types:
- String:
"Hello World" - Number:
123,45.67 - Boolean:
true,false - Null:
null - Object:
{"key": "value"} - Array:
[1, 2, 3]
Usage in Web Development:
- API data exchange between client and server
- Configuration files
- Storing structured data
- AJAX responses
- NoSQL databases (MongoDB)
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 10 - MARK DISTRIBUTION (Total: 3 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. JSON Definition & Characteristics β 1 mark β
β - What is JSON β β
β - Key characteristics β β
β - Data structure basics β β
β β β
β 2. JSON Object Structure with Examples β 1.5 marks β
β - Simple JSON object β β
β - Nested JSON object β β
β - JSON array example β β
β - Complex JSON example β β
β β β
β 3. JSON Data Types & Usage β 0.5 marks β
β - Data types enumeration β β
β - Usage in web development β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
PART B (Long Answer Questions)
Instructions: Answer any one full question from each module, each carries 14 marks.
Module I β Module I
Question 11 (14 marks) β a) How to add Hyperlinks in HTML pages? Explain internal linking in a web page with suitable example. (6 marks)
a) How to add Hyperlinks in HTML pages? Explain internal linking in a web page with suitable example. (6 marks)
Answer:
Hyperlinks in HTML:
Hyperlinks (or simply "links") are created using the anchor tag <a> in HTML. They allow users to navigate between web pages, sections within a page, or external resources. The href (Hypertext Reference) attribute specifies the destination URL or target location.
Types of Hyperlinks:
1. External Links: Link to other websites or external resources
<a href="https://www.example.com">Visit Example Website</a>
<a href="https://www.google.com" target="_blank">Open Google in New Tab</a>
2. Internal Links (Page Linking): Link to sections within the same webpage using anchor IDs
<!-- Link to a section with id="contact" -->
<a href="#contact">Go to Contact Section</a>
<!-- The target section -->
<section id="contact">
<h2>Contact Us</h2>
<p>Email: info@example.com</p>
</section>
3. Relative Links: Link to pages within the same website
<a href="about.html">About Us</a>
<a href="../index.html">Home</a>
<a href="pages/services.html">Our Services</a>
Internal Linking in Detail:
Internal linking (also called "anchor linking" or "jump links") allows navigation to specific sections within the same webpage. This is achieved using:
- Fragment identifiers (hash
#followed by element ID) - The
idattribute on target elements
Complete Example of Internal Linking:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Internal Linking Example</title>
</head>
<body>
<h1>My Portfolio</h1>
<!-- Navigation Menu with Internal Links -->
<nav>
<ul>
<li><a href="#about">About Me</a></li>
<li><a href="#education">Education</a></li>
<li><a href="#skills">Skills</a></li>
<li><a href="#projects">Projects</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
<!-- About Section -->
<section id="about">
<h2>About Me</h2>
<p>I am a web developer passionate about creating user-friendly websites.</p>
<p><a href="#top">Back to Top</a></p>
</section>
<!-- Education Section -->
<section id="education">
<h2>Education</h2>
<p>B.Tech in Computer Science and Engineering</p>
<p><a href="#top">Back to Top</a></p>
</section>
<!-- Skills Section -->
<section id="skills">
<h2>Skills</h2>
<ul>
<li>HTML5 & CSS3</li>
<li>JavaScript</li>
<li>PHP & MySQL</li>
</ul>
<p><a href="#top">Back to Top</a></p>
</section>
<!-- Projects Section -->
<section id="projects">
<h2>Projects</h2>
<p>Portfolio Website, E-commerce Application</p>
<p><a href="#top">Back to Top</a></p>
</section>
<!-- Contact Section -->
<section id="contact">
<h2>Contact</h2>
<p>Email: developer@example.com</p>
<p>Phone: +91-9876543210</p>
</section>
</body>
</html>
Key Points:
- Internal links use
href="#id"format - Target elements must have unique
idattributes - Clicking an internal link scrolls to the target section smoothly
- Useful for single-page websites, tables of contents, and navigation menus
- Improves user experience by enabling quick navigation to specific content
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 11(a) - MARK DISTRIBUTION (Total: 6 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. Hyperlink Syntax and Example β 2 marks β
β - Anchor tag <a> syntax β β
β - href attribute explanation β β
β - Basic hyperlink examples β β
β - Types of hyperlinks (external, relative) β β
β β β
β 2. Internal Linking and Example β 4 marks β
β - Internal linking concept explanation β β
β - Fragment identifiers (#id) usage β β
β - Complete working example code β β
β - Use cases and key points β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
b) Describe how you can create and structure tables in HTML. Write the HTML code for the following table (Flower Show). (8 marks)
Answer:
HTML Tables Overview:
HTML tables are used to organize and display data in rows and columns. Tables are created using a combination of tags that define the table structure, headers, rows, and cells.
Basic Table Structure Tags:
<table>- Defines the table container<thead>- Groups header content (optional but semantic)<tbody>- Groups body content (optional but semantic)<tr>- Table Row - defines a horizontal row<th>- Table Header cell - bold and centered by default<td>- Table Data cell - contains actual data<caption>- Adds a title/caption to the table (optional)
Table Attributes:
border- Adds border to table (CSS preferred)colspan- Merges cells horizontallyrowspan- Merges cells vertically
HTML Code for Flower Show Table:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flower Show Table</title>
<style>
table {
border-collapse: collapse;
width: 50%;
margin: 20px auto;
font-family: Arial, sans-serif;
}
caption {
font-size: 1.5em;
font-weight: bold;
margin-bottom: 10px;
}
th, td {
border: 2px solid #000;
padding: 10px 15px;
text-align: center;
}
th {
font-weight: bold;
}
</style>
</head>
<body>
<table>
<caption>Flower Show</caption>
<thead>
<tr>
<th colspan="2">Flower Show</th>
</tr>
<tr>
<th>Flower Name</th>
<th>Colour</th>
</tr>
</thead>
<tbody>
<tr>
<td>Red Rose</td>
<td>Red</td>
</tr>
<tr>
<td>White Rose</td>
<td rowspan="2">White</td>
</tr>
<tr>
<td>Jasmine</td>
</tr>
<tr>
<td>Sunflower</td>
<td>Yellow</td>
</tr>
</tbody>
</table>
</body>
</html>
Explanation:
-
Table Structure:
<table>creates the table container<caption>adds "Flower Show" title above the table- Semantic tags
<thead>and<tbody>organize header and body sections
-
CSS Styling:
border-collapse: collapse- Merges adjacent borders into single borders (removes double borders)border: 2px solid #000- Creates solid 2-pixel black borders for all cellspadding: 10px 15px- Adds internal spacing in cells for better readabilitytext-align: center- Centers the text within cellsfont-weight: bold- Makes header text bold
-
Header Section (
<thead>):- First row:
<th colspan="2">Flower Show</th>- merges 2 columns to create title row - Second row: Column headers "Flower Name" and "Colour"
- First row:
-
Body Section (
<tbody>):- Row 1: Red Rose | Red
- Row 2: White Rose | White (rowspan="2" merges with row 3)
- Row 3: Jasmine | (shares "White" cell from row 2)
- Row 4: Sunflower | Yellow
-
Cell Merging:
colspan="2"in first header row spans across both columnsrowspan="2"for "White" cell spans across Jasmine and White Rose rows
Simple Version (HTML only with basic border):
<table border="1" cellpadding="8" cellspacing="0">
<caption>Flower Show</caption>
<thead>
<tr>
<th colspan="2">Flower Show</th>
</tr>
<tr>
<th>Flower Name</th>
<th>Colour</th>
</tr>
</thead>
<tbody>
<tr>
<td>Red Rose</td>
<td>Red</td>
</tr>
<tr>
<td>White Rose</td>
<td rowspan="2">White</td>
</tr>
<tr>
<td>Jasmine</td>
</tr>
<tr>
<td>Sunflower</td>
<td>Yellow</td>
</tr>
</tbody>
</table>
Best Practices:
- Use
<thead>and<tbody>for semantic structure - Use
<th>for header cells (improves accessibility) - Use CSS for styling instead of deprecated HTML attributes (border, cellpadding, cellspacing)
- Use
border-collapse: collapseto merge double borders into single borders - Add padding for better visual presentation and readability
- Use semantic HTML5 elements for better document structure
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 11(b) - MARK DISTRIBUTION (Total: 8 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. Table Structure Tags Explanation β 2 marks β
β - <table>, <tr>, <th>, <td> tags β β
β - Table structure concepts β β
β - Table attributes (colspan, rowspan) β β
β β β
β 2. HTML Code for Flower Show Table β 6 marks β
β - Complete HTML structure β β
β - Correct table syntax β β
β - Proper use of colspan and rowspan β β
β - CSS styling (border-collapse, padding) β β
β - Accurate data representation β β
β - Best practices and explanations β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
Question 12 (14 marks) β a) Create a HTML form for registering to a jobsite which includes fields to enter your name, address, e-mail, contact number, a date picker to include...
a) Create a HTML form for registering to a jobsite which includes fields to enter your name, address, e-mail, contact number, a date picker to include your date of birth, radio buttons to select you sex, check boxes to show your area of interest, a selection list to input your experience with a submit and reset button. All fields must be labelled appropriately. (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>Job Registration Form</title>
</head>
<body>
<h1>Job Portal Registration</h1>
<form action="register.php" method="POST">
<!-- Name Field -->
<label for="name">Full Name:</label>
<input type="text" id="name" name="name" required>
<br><br>
<!-- Address Field -->
<label for="address">Address:</label>
<textarea id="address" name="address" rows="4" cols="50" required></textarea>
<br><br>
<!-- Email Field -->
<label for="email">E-mail:</label>
<input type="email" id="email" name="email" required>
<br><br>
<!-- Contact Number Field -->
<label for="contact">Contact Number:</label>
<input type="tel" id="contact" name="contact" pattern="[0-9]{10}" placeholder="10-digit number" required>
<br><br>
<!-- Date of Birth Picker -->
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" name="dob" required>
<br><br>
<!-- Gender Radio Buttons -->
<label>Sex:</label>
<input type="radio" id="male" name="sex" value="male" required>
<label for="male">Male</label>
<input type="radio" id="female" name="sex" value="female" required>
<label for="female">Female</label>
<input type="radio" id="other" name="sex" value="other" required>
<label for="other">Other</label>
<br><br>
<!-- Area of Interest Checkboxes -->
<label>Area of Interest:</label><br>
<input type="checkbox" id="webdev" name="interest[]" value="Web Development">
<label for="webdev">Web Development</label><br>
<input type="checkbox" id="mobile" name="interest[]" value="Mobile Development">
<label for="mobile">Mobile Development</label><br>
<input type="checkbox" id="dataScience" name="interest[]" value="Data Science">
<label for="dataScience">Data Science</label><br>
<input type="checkbox" id="cloud" name="interest[]" value="Cloud Computing">
<label for="cloud">Cloud Computing</label><br>
<input type="checkbox" id="cybersec" name="interest[]" value="Cyber Security">
<label for="cybersec">Cyber Security</label><br><br>
<!-- Experience Selection List -->
<label for="experience">Experience Level:</label>
<select id="experience" name="experience" required>
<option value="">-- Select Experience --</option>
<option value="fresher">Fresher (0 years)</option>
<option value="1-2">1-2 years</option>
<option value="3-5">3-5 years</option>
<option value="5-10">5-10 years</option>
<option value="10+">10+ years</option>
</select>
<br><br>
<!-- Submit and Reset Buttons -->
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</form>
</body>
</html>
Explanation:
1. Form Structure:
<form action="register.php" method="POST">- Submits data to server-side script- Uses POST method for secure data transmission
2. Input Fields Used:
| Field | Input Type | Attributes |
|---|---|---|
| Name | text |
required for mandatory field |
| Address | textarea |
rows, cols for multiline input |
email |
HTML5 validation for email format | |
| Contact | tel |
pattern for 10-digit validation |
| Date of Birth | date |
HTML5 date picker |
| Sex | radio |
Grouped by name="sex", only one selectable |
| Interest | checkbox |
Multiple selections allowed with name="interest[]" |
| Experience | select + option |
Dropdown list with default prompt |
| Buttons | submit / reset |
Submit sends data, Reset clears form |
3. Label Association:
<label for="id">connects labels to inputs using matchingidattributes- Improves accessibility and user experience
- Clicking label focuses the associated input
4. Form Validation:
requiredattribute makes fields mandatorytype="email"validates email format automaticallypattern="[0-9]{10}"ensures 10-digit phone numbertype="date"provides calendar widget
5. Key Features:
- All fields properly labeled as required
- Semantic HTML5 input types for better UX
- Radio buttons for mutually exclusive choice (sex)
- Checkboxes for multiple selections (interests)
- Dropdown for structured options (experience)
- Submit button to send data
- Reset button to clear all fields
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 12(a) - MARK DISTRIBUTION (Total: 8 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β Complete HTML Form with All Required Fields β 8 marks β
β - Form structure (form tag with attributes)β β
β - Name field (text input) β β
β - Address field (textarea) β β
β - Email field (email input) β β
β - Contact number field (tel input) β β
β - Date of birth (date picker) β β
β - Sex selection (radio buttons) β β
β - Area of interest (checkboxes) β β
β - Experience level (select dropdown) β β
β - Submit and Reset buttons β β
β - Proper labeling for all fields β β
β - Appropriate attributes (required, etc.) β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
b) Explain the basic concepts of the web, including the roles of a web server and a web browser. (6 marks)
Answer:
Basic Concepts of the Web:
The World Wide Web (WWW or Web) is a global information system where documents and resources are identified by URLs (Uniform Resource Locators), interconnected through hyperlinks, and accessible via the Internet using web browsers.
Core Components of the Web:
1. URLs (Uniform Resource Locators):
- Address system for web resources
- Format:
protocol://domain:port/path?query#fragment - Example:
https://www.example.com:443/page.html?id=123#section
2. HTTP/HTTPS Protocol:
- HTTP (HyperText Transfer Protocol) - Communication protocol for web
- HTTPS - Secure version with encryption (SSL/TLS)
- Defines how messages are formatted and transmitted
3. HTML (HyperText Markup Language):
- Standard markup language for creating web pages
- Structures content with tags and elements
4. Client-Server Architecture:
- Web operates on request-response model
- Clients (browsers) request resources
- Servers respond with requested content
Role of a Web Server:
A web server is a computer system (hardware) or software that stores, processes, and delivers web pages to clients over HTTP/HTTPS protocol.
Key Functions:
1. Storing Web Content:
- Hosts website files (HTML, CSS, JavaScript, images, videos)
- Maintains file directory structure
- Stores databases and application code
2. Processing Requests:
- Listens for incoming HTTP requests on specific ports (default: 80 for HTTP, 443 for HTTPS)
- Interprets request type (GET, POST, PUT, DELETE)
- Identifies requested resource from URL
3. Generating Responses:
- Retrieves static files or executes server-side scripts (PHP, Python, Node.js)
- Processes dynamic content generation
- Queries databases if needed
- Compiles response with appropriate headers and status codes
4. Sending Responses:
- Returns requested content to client
- Includes HTTP status codes:
- 200 (OK) - Success
- 404 (Not Found) - Resource doesn't exist
- 500 (Internal Server Error) - Server-side problem
5. Security Management:
- Authentication and authorization
- SSL/TLS certificate management
- Access control and firewall protection
Popular Web Servers: Apache, Nginx, Microsoft IIS, LiteSpeed
Role of a Web Browser:
A web browser is a client software application that enables users to access, retrieve, and display web content on their devices.
Key Functions:
1. Request Initiation:
- User enters URL or clicks link
- Browser creates HTTP request
- Sends request to appropriate web server via DNS resolution
2. DNS Resolution:
- Translates domain names (www.example.com) to IP addresses
- Contacts DNS servers to locate web server
3. Receiving and Processing Response:
- Receives HTML, CSS, JavaScript, images from server
- Parses HTML to build DOM (Document Object Model)
- Applies CSS for styling and layout
- Executes JavaScript for interactivity
4. Rendering Content:
- Browser rendering engine displays content visually
- Processes CSS for layout and design
- Renders text, images, videos, and interactive elements
- Ensures responsive display across screen sizes
5. User Interaction:
- Handles user inputs (clicks, form submissions, scrolling)
- Executes client-side JavaScript code
- Manages cookies and local storage
- Provides navigation controls (back, forward, refresh)
6. Security Features:
- Validates SSL/TLS certificates
- Displays security warnings for insecure sites
- Implements same-origin policy
- Blocks malicious scripts and phishing attempts
Popular Web Browsers: Google Chrome, Mozilla Firefox, Safari, Microsoft Edge, Opera
Web Communication Flow:
1. User enters URL in browser
β
2. Browser sends DNS request to find server IP
β
3. Browser sends HTTP request to web server
β
4. Web server processes request
β
5. Server executes scripts, queries database (if needed)
β
6. Server sends HTTP response with content
β
7. Browser receives response
β
8. Browser parses HTML, CSS, JavaScript
β
9. Browser renders and displays webpage
β
10. User interacts with webpage
Key Differences:
| Aspect | Web Browser | Web Server |
|---|---|---|
| Role | Client (Requester) | Server (Responder) |
| Function | Displays content | Delivers content |
| Location | User's device | Remote data center |
| Examples | Chrome, Firefox | Apache, Nginx |
| Operation | Interprets & renders | Stores & processes |
Summary:
The web functions through collaboration between browsers (clients) and servers. Browsers request and display content, while servers store and deliver resources. This client-server model, combined with HTTP protocol and URLs, forms the foundation of web communication.
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 12(b) - MARK DISTRIBUTION (Total: 6 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. Basic Concepts of the Web β 3 marks β
β - Definition of World Wide Web β β
β - Core components (URLs, HTTP/HTTPS, HTML) β β
β - Client-server architecture β β
β - Web communication flow β β
β β β
β 2. Roles of Web Server and Web Browser β 3 marks β
β - Web server definition and functions β β
β - Web browser definition and functions β β
β - Key differences comparison table β β
β - Examples of each β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
Module II β Module II
Question 13 (14 marks) β a) Explain the style specification format in CSS. Discuss the various types of CSS selectors with suitable examples. (8 marks)
a) Explain the style specification format in CSS. Discuss the various types of CSS selectors with suitable examples. (8 marks)
Answer:
CSS Style Specification Format:
CSS (Cascading Style Sheets) uses a specific syntax to define styling rules. The basic format consists of selectors and declaration blocks.
CSS Syntax Structure:
selector {
property: value;
property: value;
}
Components:
- Selector - Identifies which HTML element(s) to style
- Declaration Block - Enclosed in curly braces
{} - Property - The style attribute to modify (e.g., color, font-size)
- Value - The setting for the property (e.g., red, 16px)
- Semicolon - Separates multiple declarations
Example:
h1 {
color: blue;
font-size: 24px;
text-align: center;
}
Types of CSS Selectors:
1. Universal Selector (*)
- Selects all elements on the page
- Example:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
2. Type/Element Selector
- Selects all elements of a specific HTML tag
- Example:
p {
color: black;
line-height: 1.6;
}
h2 {
font-family: Arial, sans-serif;
color: navy;
}
3. Class Selector (.classname)
- Selects all elements with a specific class attribute
- Most commonly used selector
- Example:
.highlight {
background-color: yellow;
font-weight: bold;
}
.container {
width: 80%;
margin: 0 auto;
}
HTML:
<p class="highlight">This text is highlighted</p>
<div class="container">Content here</div>
4. ID Selector (#idname)
- Selects a unique element with specific ID
- Higher specificity than class selectors
- Should be unique on the page
- Example:
#header {
background-color: #333;
color: white;
padding: 20px;
}
#main-content {
min-height: 400px;
}
HTML:
<header id="header">Website Header</header>
<main id="main-content">Main content</main>
5. Descendant Selector (space)
- Selects elements nested inside other elements
- Example:
div p {
color: green; /* All <p> inside <div> */
}
nav ul li {
list-style: none; /* All <li> inside <ul> inside <nav> */
}
6. Child Selector (>)
- Selects direct children only (not all descendants)
- Example:
ul > li {
margin-bottom: 10px; /* Only direct <li> children of <ul> */
}
div > p {
font-size: 16px; /* Only <p> that are direct children of <div> */
}
7. Attribute Selector ([attribute])
- Selects elements based on attributes
- Example:
input[type="text"] {
border: 1px solid #ccc;
padding: 5px;
}
a[target="_blank"] {
color: red;
}
img[alt] {
border: 2px solid blue;
}
8. Pseudo-class Selector (:pseudo-class)
- Selects elements in a specific state
- Example:
a:hover {
color: red;
text-decoration: underline;
}
a:visited {
color: purple;
}
input:focus {
border-color: blue;
outline: none;
}
li:first-child {
font-weight: bold;
}
li:nth-child(odd) {
background-color: #f0f0f0;
}
9. Pseudo-element Selector (::pseudo-element)
- Styles specific parts of elements
- Example:
p::first-line {
font-weight: bold;
color: blue;
}
p::first-letter {
font-size: 2em;
float: left;
}
h2::before {
content: "βΊ ";
color: red;
}
h2::after {
content: " β";
color: red;
}
10. Grouping Selector (,)
- Applies same styles to multiple selectors
- Example:
h1, h2, h3 {
font-family: Georgia, serif;
color: navy;
}
.btn-primary, .btn-secondary, .btn-danger {
padding: 10px 20px;
border-radius: 5px;
}
11. Adjacent Sibling Selector (+)
- Selects element immediately after another
- Example:
h2 + p {
font-weight: bold; /* First <p> immediately after <h2> */
}
12. General Sibling Selector (~)
- Selects all siblings after an element
- Example:
h2 ~ p {
color: gray; /* All <p> that are siblings after <h2> */
}
Selector Specificity (Priority Order):
From highest to lowest specificity:
- Inline styles:
style="color: red;"- 1000 points - ID selectors:
#header- 100 points - Class, attribute, pseudo-class:
.menu,[type="text"],:hover- 10 points - Element, pseudo-element:
div,::before- 1 point - Universal selector:
*- 0 points
Complete Example:
/* Universal selector */
* {
margin: 0;
padding: 0;
}
/* Element selector */
body {
font-family: Arial, sans-serif;
line-height: 1.6;
}
/* Class selector */
.container {
width: 90%;
margin: 0 auto;
}
/* ID selector */
#header {
background: #333;
color: white;
}
/* Descendant selector */
nav ul li {
display: inline-block;
}
/* Pseudo-class */
a:hover {
color: red;
}
/* Attribute selector */
input[type="email"] {
border: 1px solid blue;
}
/* Grouping selector */
h1, h2, h3 {
color: navy;
}
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 13(a) - MARK DISTRIBUTION (Total: 8 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. Style specification format in CSS β 2 marks β
β - Basic CSS syntax structure β β
β - Components (selector, declaration, etc.) β β
β β β
β 2. Types of CSS selectors with examples β 6 marks β
β - Multiple selector types explained β β
β - Suitable examples provided β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
b) Using Javascript function validate an HTML form containing textboxes for entering username, password and a submit button. Validation should check the following criteria, if they're not satisfied, an alert must be given. Username must not be blank. Password must not be less than 6 characters. (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>Form Validation</title>
<script>
function validateForm() {
// Get form field values
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
// Trim whitespace from username
username = username.trim();
// Validation 1: Check if username is blank
if (username === "" || username === null) {
alert("Username must not be blank!");
document.getElementById("username").focus();
return false; // Prevent form submission
}
// Validation 2: Check if password is less than 6 characters
if (password.length < 6) {
alert("Password must not be less than 6 characters!");
document.getElementById("password").focus();
return false; // Prevent form submission
}
// If all validations pass
alert("Form submitted successfully!");
return true; // Allow form submission
}
</script>
</head>
<body>
<h2>Login Form with Validation</h2>
<form onsubmit="return validateForm()" method="post" action="login.php">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
Explanation:
1. JavaScript Validation Function:
validateForm()is called when form is submitted- Returns
trueto allow submission,falseto prevent it
2. Getting Form Values:
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
document.getElementById()accesses form elements by their ID.valueretrieves the current input value
3. Username Validation:
username = username.trim(); // Remove leading/trailing spaces
if (username === "" || username === null) {
alert("Username must not be blank!");
document.getElementById("username").focus();
return false;
}
.trim()removes whitespace- Checks if username is empty string or null
alert()displays warning message.focus()moves cursor to the fieldreturn falseprevents form submission
4. Password Length Validation:
if (password.length < 6) {
alert("Password must not be less than 6 characters!");
document.getElementById("password").focus();
return false;
}
.lengthproperty checks string length- Ensures minimum 6 characters
- Displays alert and focuses field if validation fails
5. Form Submission:
<form onsubmit="return validateForm()" method="post" action="login.php">
onsubmitevent triggers validation before submissionreturnkeyword ensures function result controls submission- Form only submits if function returns
true
Alternative: Event Listener Approach
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Validation</title>
</head>
<body>
<h2>Login Form</h2>
<form id="loginForm" method="post" action="login.php">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<br><br>
<button type="submit">Submit</button>
</form>
<script>
// Add event listener after DOM loads
document.getElementById("loginForm").addEventListener("submit", function(event) {
var username = document.getElementById("username").value.trim();
var password = document.getElementById("password").value;
// Validate username
if (username === "") {
event.preventDefault(); // Stop form submission
alert("Username must not be blank!");
document.getElementById("username").focus();
return;
}
// Validate password
if (password.length < 6) {
event.preventDefault(); // Stop form submission
alert("Password must not be less than 6 characters!");
document.getElementById("password").focus();
return;
}
// Form is valid
alert("Form submitted successfully!");
});
</script>
</body>
</html>
Key Concepts:
- Client-side validation improves user experience
- Return false or event.preventDefault() stops form submission
- focus() helps user correct errors quickly
- Should be combined with server-side validation for security
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 13(b) - MARK DISTRIBUTION (Total: 6 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. Username validation β 3 marks β
β - Check for blank/empty username β β
β - Appropriate alert message β β
β - Proper validation logic β β
β β β
β 2. Password validation β 3 marks β
β - Check minimum 6 characters β β
β - Appropriate alert message β β
β - Proper validation logic β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
Question 14 (14 marks) β a) Organize a sample web page for the Technical event at your campus and use embedded Style sheet to apply minimum of eight style properties. State th...
a) Organize a sample web page for the Technical event at your campus and use embedded Style sheet to apply minimum of eight style properties. State the Style Specification format of embedded style sheet. (8 marks)
Answer:
Embedded Style Sheet Specification Format:
An embedded (or internal) style sheet is defined within the <style> tag in the <head> section of an HTML document. It applies styles only to that specific HTML page.
Format:
<head>
<style>
selector {
property: value;
property: value;
}
</style>
</head>
Characteristics:
- Placed in
<head>section - Enclosed in
<style>tags - Affects only the current HTML document
- Higher priority than external stylesheets
- Lower priority than inline styles
Complete Web Page for Technical Event:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TechFest 2025 - Campus Technical Event</title>
<style>
/* Style Property 1: Body background color and font */
body {
background-color: #f4f4f4;
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
/* Style Property 2: Header styling with background and padding */
header {
background-color: #2c3e50;
color: white;
text-align: center;
padding: 30px 0;
}
/* Style Property 3: Heading font size and text transformation */
h1 {
font-size: 36px;
text-transform: uppercase;
margin: 0;
}
/* Style Property 4: Container width and centering */
.container {
width: 80%;
margin: 30px auto;
background-color: white;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
/* Style Property 5: Section headings with border */
h2 {
color: #2c3e50;
border-bottom: 3px solid #3498db;
padding-bottom: 10px;
font-size: 28px;
}
/* Style Property 6: Paragraph line height and text alignment */
p {
line-height: 1.8;
text-align: justify;
color: #333;
}
/* Style Property 7: List styling with custom bullets */
ul {
list-style-type: square;
color: #555;
padding-left: 40px;
}
/* Style Property 8: Link styling with hover effect */
a {
color: #3498db;
text-decoration: none;
font-weight: bold;
}
a:hover {
color: #e74c3c;
text-decoration: underline;
}
/* Additional: Footer styling */
footer {
background-color: #34495e;
color: white;
text-align: center;
padding: 15px 0;
margin-top: 30px;
}
/* Additional: Event details table-like styling */
.event-info {
background-color: #ecf0f1;
padding: 15px;
border-radius: 5px;
margin: 20px 0;
}
</style>
</head>
<body>
<header>
<h1>TechFest 2025</h1>
<p>Annual Technical Symposium</p>
</header>
<div class="container">
<h2>About the Event</h2>
<p>
TechFest 2025 is our college's premier technical symposium, bringing together
students, faculty, and industry professionals to celebrate innovation and
technology. This year's event features cutting-edge competitions, workshops,
guest lectures, and project exhibitions across multiple domains of computer
science and engineering.
</p>
<div class="event-info">
<strong>Date:</strong> March 15-17, 2025<br>
<strong>Venue:</strong> College Auditorium and Labs<br>
<strong>Registration Fee:</strong> βΉ200 per participant<br>
<strong>Contact:</strong> techfest2025@college.edu
</div>
<h2>Events and Competitions</h2>
<ul>
<li><strong>Code Sprint:</strong> 24-hour coding marathon</li>
<li><strong>Web Warriors:</strong> Web development competition</li>
<li><strong>AI Challenge:</strong> Machine learning problem solving</li>
<li><strong>Hack-a-thon:</strong> Innovative solution development</li>
<li><strong>Project Expo:</strong> Display your innovative projects</li>
<li><strong>Tech Quiz:</strong> Test your technical knowledge</li>
<li><strong>Paper Presentation:</strong> Present research papers</li>
</ul>
<h2>Guest Speakers</h2>
<p>
We are honored to host distinguished speakers from leading tech companies
including Google, Microsoft, and Amazon. Industry experts will share insights
on emerging technologies, career guidance, and the future of software engineering.
</p>
<h2>Registration</h2>
<p>
Register now to secure your spot! Early bird registration ends on February 28, 2025.
Visit our registration portal or contact the event coordinators for more information.
<br><br>
<a href="register.html">Click here to Register</a>
</p>
<h2>Workshops</h2>
<ul>
<li>Full Stack Web Development</li>
<li>Cloud Computing with AWS</li>
<li>Introduction to Machine Learning</li>
<li>Mobile App Development</li>
<li>Cyber Security Fundamentals</li>
</ul>
</div>
<footer>
<p>© 2025 TechFest - College of Engineering | All Rights Reserved</p>
<p>Follow us: <a href="#">Facebook</a> | <a href="#">Twitter</a> | <a href="#">Instagram</a></p>
</footer>
</body>
</html>
Eight Style Properties Applied:
background-color- Sets background colors for body, header, container sectionsfont-family- Defines typography (Arial, sans-serif)text-align- Centers header text and justifies paragraphspadding- Adds internal spacing to header, container, sectionsfont-size- Controls text size for h1 (36px) and h2 (28px)color- Sets text colors for various elementsborder-bottom- Adds decorative underline to h2 elementsline-height- Improves paragraph readability (1.8)text-transform- Converts h1 to uppercasebox-shadow- Adds depth to container with shadow effect
Additional Properties Used:
margin- Controls external spacingwidth- Sets container width to 80%list-style-type- Custom bullet style for liststext-decoration- Removes underline from links initiallyborder-radius- Rounds corners of event-info box
Style Specification Format Explanation:
selector {
property1: value1;
property2: value2;
}
Example from the code:
h1 {
font-size: 36px; /* Property 1 */
text-transform: uppercase; /* Property 2 */
margin: 0; /* Property 3 */
}
Benefits of Embedded Stylesheets:
- Keeps styles with the document
- No additional HTTP requests (faster than external CSS for single page)
- Easier to manage for single-page documents
- Higher specificity than external stylesheets
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 14(a) - MARK DISTRIBUTION (Total: 8 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. Embedded style sheet implementation β 8 marks β
β - Proper embedded style sheet format β β
β - Complete web page for technical event β β
β - Minimum eight style properties applied β β
β - Correct CSS syntax and structure β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
b) Illustrate the usage of JavaScript DOM in event handling with examples. (6 marks)
Answer:
JavaScript DOM (Document Object Model):
The DOM is a programming interface for HTML documents. It represents the page structure as a tree of objects, allowing JavaScript to access and manipulate HTML elements, attributes, styles, and content dynamically.
DOM Event Handling:
Events are actions that occur in the browser, such as clicks, mouse movements, key presses, form submissions, and page loading. JavaScript can "listen" for these events and execute code in response.
Common DOM Events:
- Mouse Events:
click,dblclick,mouseover,mouseout,mousedown,mouseup - Keyboard Events:
keydown,keyup,keypress - Form Events:
submit,change,focus,blur - Window Events:
load,resize,scroll
Methods of Event Handling:
1. Inline Event Handlers (Not Recommended)
<button onclick="alert('Button clicked!')">Click Me</button>
2. DOM Event Properties
element.onclick = function() { /* code */ };
3. addEventListener() Method (Recommended)
element.addEventListener('click', function() { /* code */ });
Complete Examples:
Example 1: Click Event - Change Text and Style
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Click Event Example</title>
</head>
<body>
<h2 id="heading">Welcome to JavaScript DOM</h2>
<button id="changeBtn">Change Text</button>
<button id="colorBtn">Change Color</button>
<script>
// Get DOM elements
var heading = document.getElementById("heading");
var changeBtn = document.getElementById("changeBtn");
var colorBtn = document.getElementById("colorBtn");
// Click event to change text
changeBtn.addEventListener('click', function() {
heading.textContent = "Text Changed Successfully!";
heading.style.fontStyle = "italic";
});
// Click event to change color
colorBtn.addEventListener('click', function() {
heading.style.color = "red";
heading.style.backgroundColor = "yellow";
});
</script>
</body>
</html>
Explanation:
getElementById()selects elements by their IDaddEventListener('click', function)attaches click event handlertextContentmodifies element textstyleproperty accesses CSS styling
Example 2: Mouse Events - Hover Effects
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mouse Events</title>
<style>
#box {
width: 200px;
height: 200px;
background-color: lightblue;
text-align: center;
line-height: 200px;
font-size: 20px;
transition: all 0.3s;
}
</style>
</head>
<body>
<div id="box">Hover over me!</div>
<p id="status">Status: Waiting...</p>
<script>
var box = document.getElementById("box");
var status = document.getElementById("status");
// Mouseover event
box.addEventListener('mouseover', function() {
box.style.backgroundColor = "coral";
box.style.transform = "scale(1.1)";
status.textContent = "Status: Mouse is over the box";
});
// Mouseout event
box.addEventListener('mouseout', function() {
box.style.backgroundColor = "lightblue";
box.style.transform = "scale(1)";
status.textContent = "Status: Mouse left the box";
});
// Click event
box.addEventListener('click', function() {
alert("Box was clicked!");
});
</script>
</body>
</html>
Example 3: Keyboard Events - Input Validation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Keyboard Events</title>
</head>
<body>
<h3>Type in the input box:</h3>
<input type="text" id="textInput" placeholder="Start typing...">
<p id="output">You typed: </p>
<p id="charCount">Character count: 0</p>
<script>
var textInput = document.getElementById("textInput");
var output = document.getElementById("output");
var charCount = document.getElementById("charCount");
// Keyup event - triggers after key is released
textInput.addEventListener('keyup', function() {
var text = textInput.value;
output.textContent = "You typed: " + text;
charCount.textContent = "Character count: " + text.length;
});
// Keypress event - triggers when key is pressed
textInput.addEventListener('keypress', function(event) {
console.log("Key pressed: " + event.key);
});
</script>
</body>
</html>
Example 4: Form Events - Dynamic Validation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Events</title>
<style>
.error { border: 2px solid red; }
.valid { border: 2px solid green; }
.message { font-size: 12px; margin-top: 5px; }
</style>
</head>
<body>
<h3>Registration Form</h3>
<form id="registrationForm">
<label for="email">Email:</label>
<input type="text" id="email" name="email">
<p id="emailMsg" class="message"></p>
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<p id="passMsg" class="message"></p>
<br><br>
<button type="submit">Submit</button>
</form>
<script>
var emailInput = document.getElementById("email");
var passwordInput = document.getElementById("password");
var emailMsg = document.getElementById("emailMsg");
var passMsg = document.getElementById("passMsg");
var form = document.getElementById("registrationForm");
// Focus event - triggered when input gets focus
emailInput.addEventListener('focus', function() {
emailMsg.textContent = "Enter a valid email address";
emailMsg.style.color = "blue";
});
// Blur event - triggered when input loses focus
emailInput.addEventListener('blur', function() {
var email = emailInput.value;
var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (emailPattern.test(email)) {
emailInput.className = "valid";
emailMsg.textContent = "Valid email!";
emailMsg.style.color = "green";
} else {
emailInput.className = "error";
emailMsg.textContent = "Invalid email format!";
emailMsg.style.color = "red";
}
});
// Input event - triggers on every input change
passwordInput.addEventListener('input', function() {
var passLength = passwordInput.value.length;
if (passLength < 6) {
passMsg.textContent = "Password too short (minimum 6 characters)";
passMsg.style.color = "red";
passwordInput.className = "error";
} else {
passMsg.textContent = "Password strength: Good";
passMsg.style.color = "green";
passwordInput.className = "valid";
}
});
// Submit event - form submission handling
form.addEventListener('submit', function(event) {
event.preventDefault(); // Prevent actual form submission
if (emailInput.className === "valid" && passwordInput.className === "valid") {
alert("Form submitted successfully!");
} else {
alert("Please fill all fields correctly!");
}
});
</script>
</body>
</html>
Example 5: Event Object - Getting Event Information
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Event Object</title>
</head>
<body>
<button id="eventBtn">Click Me</button>
<p id="info"></p>
<script>
var btn = document.getElementById("eventBtn");
var info = document.getElementById("info");
btn.addEventListener('click', function(event) {
var eventInfo =
"Event Type: " + event.type + "<br>" +
"Target Element: " + event.target.tagName + "<br>" +
"Click X: " + event.clientX + "<br>" +
"Click Y: " + event.clientY + "<br>" +
"Timestamp: " + event.timeStamp;
info.innerHTML = eventInfo;
});
</script>
</body>
</html>
Key Concepts:
1. Accessing Elements:
document.getElementById("id")
document.getElementsByClassName("class")
document.getElementsByTagName("tag")
document.querySelector(".class")
document.querySelectorAll(".class")
2. Event Listener Syntax:
element.addEventListener(eventType, function, useCapture);
3. Event Object Properties:
event.type- Type of event (click, keyup, etc.)event.target- Element that triggered the eventevent.preventDefault()- Cancels default actionevent.stopPropagation()- Stops event bubbling
4. Manipulating DOM:
element.textContent- Change textelement.innerHTML- Change HTML contentelement.style.property- Modify CSSelement.className- Change classelement.setAttribute()- Set attributes
Benefits of DOM Event Handling:
- Interactive user experiences
- Dynamic content updates without page reload
- Form validation and feedback
- Responsive user interfaces
- Real-time data processing
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 14(b) - MARK DISTRIBUTION (Total: 6 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. DOM Event Handling explanation β 3 marks β
β - Concept of DOM events β β
β - Event types and usage β β
β β β
β 2. Methods and Examples β 3 marks β
β - Event handling methods β β
β - Practical examples with code β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
Module III β Module III
Question 15 (14 marks) β a) Write a PHP program that defines a user-defined function 'Calculator' which will accept two input values through an HTML form and perform four basi...
a) Write a PHP program that defines a user-defined function 'Calculator' which will accept two input values through an HTML form and perform four basic mathematical operations. (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>PHP Calculator</title>
</head>
<body>
<h2>PHP Calculator - Four Basic Operations</h2>
<form method="POST" action="">
<label for="num1">Enter First Number:</label>
<input type="number" step="any" id="num1" name="num1" required>
<br><br>
<label for="num2">Enter Second Number:</label>
<input type="number" step="any" id="num2" name="num2" required>
<br><br>
<button type="submit" name="calculate">Calculate</button>
</form>
<?php
// User-defined Calculator function
function Calculator($num1, $num2) {
echo "<h3>Calculation Results:</h3>";
echo "<table border='1' cellpadding='10' cellspacing='0'>";
echo "<tr><th>Operation</th><th>Result</th></tr>";
// Addition
$addition = $num1 + $num2;
echo "<tr><td>$num1 + $num2</td><td>$addition</td></tr>";
// Subtraction
$subtraction = $num1 - $num2;
echo "<tr><td>$num1 - $num2</td><td>$subtraction</td></tr>";
// Multiplication
$multiplication = $num1 * $num2;
echo "<tr><td>$num1 Γ $num2</td><td>$multiplication</td></tr>";
// Division (with zero check)
if ($num2 != 0) {
$division = $num1 / $num2;
echo "<tr><td>$num1 Γ· $num2</td><td>" . number_format($division, 2) . "</td></tr>";
} else {
echo "<tr><td>$num1 Γ· $num2</td><td style='color: red;'>Cannot divide by zero</td></tr>";
}
echo "</table>";
}
// Process form submission
if (isset($_POST['calculate'])) {
// Get input values from form
$number1 = $_POST['num1'];
$number2 = $_POST['num2'];
// Validate inputs
if (is_numeric($number1) && is_numeric($number2)) {
// Call Calculator function
Calculator($number1, $number2);
} else {
echo "<p style='color: red;'>Please enter valid numbers!</p>";
}
}
?>
</body>
</html>
Explanation:
1. HTML Form Structure:
- Form uses
POSTmethod for data submission - Two input fields with
type="number"for numeric input step="any"allows decimal numbersrequiredattribute ensures fields are not empty- Submit button named "calculate"
2. Calculator Function Definition:
function Calculator($num1, $num2) {
// Performs four operations and displays results
}
- User-defined function that accepts two parameters
- Performs all four basic mathematical operations
- Displays results in a formatted HTML table
3. Four Basic Operations:
a) Addition:
$addition = $num1 + $num2;
b) Subtraction:
$subtraction = $num1 - $num2;
c) Multiplication:
$multiplication = $num1 * $num2;
d) Division:
if ($num2 != 0) {
$division = $num1 / $num2;
} else {
// Handle division by zero error
}
- Includes validation to prevent division by zero
- Uses
number_format()to display result with 2 decimal places
4. Form Processing:
if (isset($_POST['calculate'])) {
$number1 = $_POST['num1'];
$number2 = $_POST['num2'];
if (is_numeric($number1) && is_numeric($number2)) {
Calculator($number1, $number2);
}
}
- Checks if form is submitted using
isset() - Retrieves values from
$_POSTsuperglobal - Validates inputs using
is_numeric() - Calls Calculator function with validated inputs
5. Key Features:
- Single page application (form and PHP code in same file)
- Input validation for security
- Division by zero error handling
- Professional table formatting for results
- Number formatting for better readability
Test Cases:
Input: num1 = 20, num2 = 5
Output:
20 + 5 = 25
20 - 5 = 15
20 Γ 5 = 100
20 Γ· 5 = 4.00
Input: num1 = 15, num2 = 0
Output:
15 + 0 = 15
15 - 0 = 15
15 Γ 0 = 0
15 Γ· 0 = Cannot divide by zero
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 15(a) - MARK DISTRIBUTION (Total: 8 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. Calculator user-defined function β 4 marks β
β - Function definition and structure β β
β - Four mathematical operations β β
β - Proper PHP syntax β β
β β β
β 2. HTML input form β 4 marks β
β - Form structure with two input fields β β
β - Submit button implementation β β
β - Form processing logic β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
b) What is a cookie? How does PHP support the concept of cookies? Explain the difference between sessions and cookies. (6 marks)
Answer:
What is a Cookie?
A cookie is a small text file (typically 4KB or less) stored on the client's (user's) browser by the web server. Cookies are used to remember information about the user between HTTP requests, enabling stateful interactions in the otherwise stateless HTTP protocol.
Purpose of Cookies:
- Remember user preferences (language, theme, etc.)
- Track user sessions and login status
- Store shopping cart items
- Personalize user experience
- Analytics and tracking
PHP Cookie Support:
PHP provides built-in functions to create, access, modify, and delete cookies.
1. Setting a Cookie - setcookie()
Syntax:
setcookie(name, value, expire, path, domain, secure, httponly);
Parameters:
name- Name of the cookie (required)value- Value stored in cookie (required)expire- Expiration time as Unix timestamp (optional)path- Server path where cookie is available (optional, default:/)domain- Domain where cookie is valid (optional)secure- If true, cookie only sent over HTTPS (optional)httponly- If true, cookie accessible only through HTTP protocol (optional)
Example - Creating Cookies:
<?php
// Set a cookie that expires in 1 hour
setcookie("username", "John Doe", time() + 3600, "/");
// Set a cookie that expires in 30 days
setcookie("user_preference", "dark_mode", time() + (30 * 24 * 60 * 60), "/");
// Set a cookie with all parameters
setcookie("user_id", "12345", time() + 86400, "/", "example.com", true, true);
echo "Cookies have been set!";
?>
Important: setcookie() must be called before any output is sent to the browser (before HTML, echo, etc.)
2. Accessing/Reading Cookies - $_COOKIE
<?php
// Check if cookie exists and read its value
if (isset($_COOKIE['username'])) {
echo "Welcome back, " . $_COOKIE['username'];
} else {
echo "Welcome, Guest!";
}
// Read multiple cookies
$username = isset($_COOKIE['username']) ? $_COOKIE['username'] : "Guest";
$theme = isset($_COOKIE['user_preference']) ? $_COOKIE['user_preference'] : "light_mode";
echo "User: $username, Theme: $theme";
?>
3. Modifying a Cookie
To modify a cookie, simply set it again with the same name but different value:
<?php
// Update the username cookie
setcookie("username", "Jane Smith", time() + 3600, "/");
?>
4. Deleting a Cookie
Set the expiration time to a past timestamp:
<?php
// Delete the username cookie
setcookie("username", "", time() - 3600, "/");
// Alternative method
setcookie("username", null, time() - 3600, "/");
?>
Complete Cookie Example:
<?php
// Set cookie when form is submitted
if (isset($_POST['save_name'])) {
$name = $_POST['name'];
// Set cookie for 1 day
setcookie("visitor_name", $name, time() + 86400, "/");
header("Location: " . $_SERVER['PHP_SELF']); // Refresh page
exit;
}
// Delete cookie if requested
if (isset($_GET['logout'])) {
setcookie("visitor_name", "", time() - 3600, "/");
header("Location: " . $_SERVER['PHP_SELF']);
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Cookie Example</title>
</head>
<body>
<?php if (isset($_COOKIE['visitor_name'])): ?>
<h2>Welcome back, <?php echo htmlspecialchars($_COOKIE['visitor_name']); ?>!</h2>
<a href="?logout=true">Logout</a>
<?php else: ?>
<h2>Enter your name:</h2>
<form method="POST">
<input type="text" name="name" required>
<button type="submit" name="save_name">Save</button>
</form>
<?php endif; ?>
</body>
</html>
Difference Between Sessions and Cookies:
| Aspect | Cookies | Sessions |
|---|---|---|
| Storage Location | Client-side (user's browser) | Server-side (web server) |
| Data Size | Limited (4KB typically) | Larger (limited by server memory) |
| Security | Less secure (visible to user) | More secure (data hidden from user) |
| Lifetime | Persistent (can last days/months) | Temporary (ends when browser closes) |
| Access | Accessible via $_COOKIE |
Accessible via $_SESSION |
| Speed | Slower (sent with every HTTP request) | Faster (only session ID transmitted) |
| Expiration | Set by developer | Ends with browser close or timeout |
| Data Type | Strings only | Any PHP data type (arrays, objects) |
| Use Case | Remember preferences, tracking | Login authentication, shopping carts |
| Function | setcookie(), $_COOKIE |
session_start(), $_SESSION |
Cookie Example:
<?php
// Setting cookie
setcookie("color_preference", "blue", time() + 86400);
// Reading cookie
if (isset($_COOKIE['color_preference'])) {
echo "Your favorite color is: " . $_COOKIE['color_preference'];
}
?>
Session Example:
<?php
// Start session
session_start();
// Setting session variable
$_SESSION['username'] = "John";
$_SESSION['user_id'] = 101;
// Reading session variable
if (isset($_SESSION['username'])) {
echo "Logged in as: " . $_SESSION['username'];
}
// Destroying session
session_destroy();
?>
When to Use Cookies vs Sessions:
Use Cookies when:
- Storing non-sensitive user preferences (theme, language)
- Remember Me functionality
- Tracking user behavior across visits
- Data needs to persist after browser close
Use Sessions when:
- Storing sensitive data (user authentication)
- Data needed only during current browsing session
- Shopping cart items (temporary)
- Large amounts of data
- Better security is required
Best Practice: Combine both - use sessions for sensitive data and cookies to maintain session ID:
<?php
session_start(); // Uses cookie to store session ID
$_SESSION['user_id'] = 123; // Actual data stored on server
?>
Summary:
Cookies store data on the client browser with limited size and security, while sessions store data on the server with a session ID cookie linking the user to their server-side data. Sessions are more secure and flexible, while cookies are better for persistent, non-sensitive data.
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 15(b) - MARK DISTRIBUTION (Total: 6 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. Cookie definition and usage β 3 marks β
β - What is a cookie β β
β - PHP cookie support (setcookie, $_COOKIE) β β
β - Cookie operations and examples β β
β β β
β 2. Difference between cookies and sessions β 3 marks β
β - Comparison of key aspects β β
β - Storage, security, lifetime differences β β
β - Use cases for each β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
Question 16 (14 marks) β a) Discuss the flow control functions and control statements in PHP. (8 marks)
a) Discuss the flow control functions and control statements in PHP. (8 marks)
Answer:
Flow Control in PHP:
Flow control determines the order in which statements are executed in a program. PHP provides various control structures to manage program flow based on conditions, loops, and decisions.
1. Conditional Statements
a) if Statement:
Executes code block if condition is true.
Syntax:
if (condition) {
// code to execute if condition is true
}
Example:
<?php
$age = 20;
if ($age >= 18) {
echo "You are eligible to vote";
}
?>
b) if-else Statement:
Executes one block if condition is true, another if false.
Syntax:
if (condition) {
// code if true
} else {
// code if false
}
Example:
<?php
$number = 15;
if ($number % 2 == 0) {
echo "$number is even";
} else {
echo "$number is odd";
}
// Output: 15 is odd
?>
c) if-elseif-else Statement:
Tests multiple conditions sequentially.
Syntax:
if (condition1) {
// code if condition1 is true
} elseif (condition2) {
// code if condition2 is true
} else {
// code if all conditions are false
}
Example:
<?php
$marks = 75;
if ($marks >= 90) {
$grade = "A+";
} elseif ($marks >= 80) {
$grade = "A";
} elseif ($marks >= 70) {
$grade = "B";
} elseif ($marks >= 60) {
$grade = "C";
} else {
$grade = "F";
}
echo "Marks: $marks, Grade: $grade";
// Output: Marks: 75, Grade: B
?>
d) switch Statement:
Executes different code blocks based on value of an expression.
Syntax:
switch (expression) {
case value1:
// code for value1
break;
case value2:
// code for value2
break;
default:
// code if no case matches
}
Example:
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the work week";
break;
case "Friday":
echo "End of the work week";
break;
case "Saturday":
case "Sunday":
echo "Weekend!";
break;
default:
echo "Midweek day";
}
// Output: Start of the work week
?>
Important: break statement prevents fall-through to next case.
2. Looping Statements
a) while Loop:
Executes code block while condition is true. Condition checked before execution.
Syntax:
while (condition) {
// code to repeat
}
Example:
<?php
$count = 1;
while ($count <= 5) {
echo "Count: $count<br>";
$count++;
}
// Output: Count: 1, Count: 2, Count: 3, Count: 4, Count: 5
?>
b) do-while Loop:
Executes code block at least once, then repeats while condition is true. Condition checked after execution.
Syntax:
do {
// code to execute
} while (condition);
Example:
<?php
$num = 1;
do {
echo "$num ";
$num++;
} while ($num <= 5);
// Output: 1 2 3 4 5
// Executes at least once even if condition is false
$x = 10;
do {
echo "Executed once";
} while ($x < 5); // Condition false, but code still runs once
?>
c) for Loop:
Used when number of iterations is known. Includes initialization, condition, and increment in one line.
Syntax:
for (initialization; condition; increment) {
// code to repeat
}
Example:
<?php
// 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 even numbers
for ($i = 2; $i <= 20; $i += 2) {
echo "$i ";
}
// Output: 2 4 6 8 10 12 14 16 18 20
// Multiplication table
$num = 5;
for ($i = 1; $i <= 10; $i++) {
echo "$num Γ $i = " . ($num * $i) . "<br>";
}
?>
d) foreach Loop:
Specifically designed for iterating over arrays and objects.
Syntax:
// For indexed arrays
foreach ($array as $value) {
// code using $value
}
// For associative arrays
foreach ($array as $key => $value) {
// code using $key and $value
}
Example:
<?php
// Indexed array
$colors = array("Red", "Green", "Blue", "Yellow");
foreach ($colors as $color) {
echo "$color<br>";
}
// Associative array
$student = array(
"name" => "John",
"age" => 20,
"course" => "CST463"
);
foreach ($student as $key => $value) {
echo "$key: $value<br>";
}
// Output:
// name: John
// age: 20
// course: CST463
?>
3. Jump Statements
a) break Statement:
Exits from loop or switch statement immediately.
Example:
<?php
// Exit loop when number is 5
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break; // Exit loop
}
echo "$i ";
}
// Output: 1 2 3 4
// Break from nested loops
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 3; $j++) {
if ($j == 2) {
break; // Breaks inner loop only
}
echo "($i, $j) ";
}
}
?>
b) continue Statement:
Skips current iteration and continues with next iteration.
Example:
<?php
// Skip even numbers
for ($i = 1; $i <= 10; $i++) {
if ($i % 2 == 0) {
continue; // Skip even numbers
}
echo "$i ";
}
// Output: 1 3 5 7 9
// Skip specific value
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue; // Skip when i is 3
}
echo "$i ";
}
// Output: 1 2 4 5
?>
c) return Statement:
Exits from function and optionally returns a value.
Example:
<?php
function checkEven($num) {
if ($num % 2 == 0) {
return true;
} else {
return false;
}
}
$result = checkEven(10);
echo $result ? "Even" : "Odd"; // Output: Even
?>
d) exit() and die() Functions:
Terminates script execution immediately.
Example:
<?php
$age = 15;
if ($age < 18) {
die("Access denied. You must be 18 or older.");
}
echo "Welcome!"; // This won't execute if age < 18
?>
4. Alternative Syntax for Control Structures
PHP also supports alternative syntax using colons:
<?php
// Alternative if syntax
if ($condition):
// code
elseif ($condition2):
// code
else:
// code
endif;
// Alternative while syntax
while ($condition):
// code
endwhile;
// Alternative for syntax
for ($i = 0; $i < 10; $i++):
// code
endfor;
// Alternative foreach syntax
foreach ($array as $value):
// code
endforeach;
// Alternative switch syntax
switch ($var):
case 1:
// code
break;
default:
// code
endswitch;
?>
5. Nested Control Structures
Control structures can be nested within each other:
<?php
// Nested loops - Print multiplication table
for ($i = 1; $i <= 5; $i++) {
for ($j = 1; $j <= 5; $j++) {
echo ($i * $j) . "\t";
}
echo "<br>";
}
// Nested if-else
$age = 25;
$citizen = true;
if ($age >= 18) {
if ($citizen) {
echo "Eligible to vote";
} else {
echo "Not a citizen";
}
} else {
echo "Too young to vote";
}
?>
Complete Example - Flow Control:
<?php
// Student grade calculator using multiple control structures
$students = array(
array("name" => "Alice", "marks" => 85),
array("name" => "Bob", "marks" => 72),
array("name" => "Charlie", "marks" => 55),
array("name" => "David", "marks" => 92)
);
echo "<h3>Student Grade Report</h3>";
echo "<table border='1'>";
echo "<tr><th>Name</th><th>Marks</th><th>Grade</th><th>Status</th></tr>";
foreach ($students as $student) {
$name = $student['name'];
$marks = $student['marks'];
// Determine grade using if-elseif-else
if ($marks >= 90) {
$grade = "A+";
} elseif ($marks >= 80) {
$grade = "A";
} elseif ($marks >= 70) {
$grade = "B";
} elseif ($marks >= 60) {
$grade = "C";
} else {
$grade = "F";
}
// Determine status using switch
switch ($grade) {
case "A+":
case "A":
$status = "Excellent";
break;
case "B":
$status = "Good";
break;
case "C":
$status = "Pass";
break;
default:
$status = "Fail";
}
echo "<tr><td>$name</td><td>$marks</td><td>$grade</td><td>$status</td></tr>";
}
echo "</table>";
?>
Summary:
PHP flow control provides powerful mechanisms to control program execution through conditional statements (if, switch), loops (while, do-while, for, foreach), and jump statements (break, continue, return). These structures enable developers to create dynamic, responsive applications that can make decisions and process data efficiently.
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 16(a) - MARK DISTRIBUTION (Total: 8 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. Flow Control Functions and Statements β 8 marks β
β - Conditional statements (if, switch) β β
β - Loop statements (while, for, foreach) β β
β - Jump statements (break, continue) β β
β - Examples and syntax demonstrations β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
b) Discuss string processing in PHP with examples. (6 marks)
Answer:
String Processing in PHP:
PHP provides extensive built-in functions for string manipulation, making it powerful for text processing, validation, and formatting.
1. String Creation and Declaration:
<?php
// Single quotes - literal string
$str1 = 'Hello World';
// Double quotes - interprets variables
$name = "John";
$str2 = "Hello, $name"; // Output: Hello, John
// Heredoc syntax - for multi-line strings
$text = <<<EOT
This is a multi-line
string using heredoc
syntax.
EOT;
// Nowdoc syntax - like single quotes, no variable interpretation
$text2 = <<<'EOT'
This is $name
EOT;
// Output: This is $name (literal)
?>
2. String Length and Character Access:
<?php
// strlen() - Get string length
$text = "Web Programming";
echo strlen($text); // Output: 15
// Access individual characters
$str = "Hello";
echo $str[0]; // Output: H
echo $str[4]; // Output: o
// Modify characters
$str[0] = 'J';
echo $str; // Output: Jello
?>
3. String Case Manipulation:
<?php
$text = "Web Programming CST463";
// strtoupper() - Convert to uppercase
echo strtoupper($text); // Output: WEB PROGRAMMING CST463
// strtolower() - Convert to lowercase
echo strtolower($text); // Output: web programming cst463
// ucfirst() - Capitalize first character
echo ucfirst("hello"); // Output: Hello
// ucwords() - Capitalize first character of each word
echo ucwords("web programming"); // Output: Web Programming
// lcfirst() - Lowercase first character
echo lcfirst("Hello"); // Output: hello
?>
4. String Trimming:
<?php
$text = " Hello World ";
// trim() - Remove whitespace from both ends
echo trim($text); // Output: "Hello World"
// ltrim() - Remove whitespace from left
echo ltrim($text); // Output: "Hello World "
// rtrim() - Remove whitespace from right
echo rtrim($text); // Output: " Hello World"
// Remove specific characters
$str = "###Hello###";
echo trim($str, "#"); // Output: Hello
?>
5. String Search and Position:
<?php
$text = "PHP is a server-side scripting language";
// strpos() - Find first occurrence (case-sensitive)
$pos = strpos($text, "server");
echo $pos; // Output: 10
// stripos() - Find first occurrence (case-insensitive)
$pos2 = stripos($text, "SERVER");
echo $pos2; // Output: 10
// strrpos() - Find last occurrence
$text2 = "Hello Hello Hello";
echo strrpos($text2, "Hello"); // Output: 12
// str_contains() - Check if string contains substring (PHP 8+)
if (str_contains($text, "PHP")) {
echo "Found!";
}
// strstr() - Find substring and return remainder
echo strstr($text, "server"); // Output: server-side scripting language
?>
6. String Replacement:
<?php
// str_replace() - Replace all occurrences
$text = "I love JavaScript and JavaScript is great";
$newText = str_replace("JavaScript", "PHP", $text);
echo $newText; // Output: I love PHP and PHP is great
// str_ireplace() - Case-insensitive replacement
$text2 = "Hello HELLO hello";
echo str_ireplace("hello", "Hi", $text2); // Output: Hi Hi Hi
// Replace multiple values
$text3 = "Apples and Oranges";
$newText3 = str_replace(array("Apples", "Oranges"), array("Bananas", "Grapes"), $text3);
echo $newText3; // Output: Bananas and Grapes
// substr_replace() - Replace part of string
$str = "Hello World";
echo substr_replace($str, "PHP", 6); // Output: Hello PHP
?>
7. String Extraction (Substring):
<?php
$text = "PHP Programming";
// substr() - Extract substring
echo substr($text, 0, 3); // Output: PHP (from index 0, length 3)
echo substr($text, 4); // Output: Programming (from index 4 to end)
echo substr($text, -11); // Output: Programming (11 characters from end)
echo substr($text, 0, -12); // Output: PHP (from start, excluding last 12)
// str_split() - Split string into array
$chars = str_split("Hello", 2);
print_r($chars); // Output: Array([0] => He [1] => ll [2] => o)
?>
8. String Splitting and Joining:
<?php
// explode() - Split string into array by delimiter
$fruits = "Apple,Banana,Orange,Mango";
$fruitArray = explode(",", $fruits);
print_r($fruitArray);
// Output: Array([0] => Apple [1] => Banana [2] => Orange [3] => Mango)
// implode() / join() - Join array elements into string
$colors = array("Red", "Green", "Blue");
$colorString = implode(", ", $colors);
echo $colorString; // Output: Red, Green, Blue
// str_split() - Convert string to array of characters
$word = "Hello";
$letters = str_split($word);
print_r($letters); // Output: Array([0] => H [1] => e [2] => l [3] => l [4] => o)
?>
9. String Comparison:
<?php
$str1 = "Hello";
$str2 = "hello";
// strcmp() - Case-sensitive comparison
// Returns 0 if equal, <0 if str1 < str2, >0 if str1 > str2
echo strcmp($str1, $str2); // Output: -32 (not equal)
// strcasecmp() - Case-insensitive comparison
echo strcasecmp($str1, $str2); // Output: 0 (equal)
// Using comparison operators
if ($str1 == $str2) {
echo "Equal";
} else {
echo "Not equal"; // This executes
}
// strncmp() - Compare first n characters
echo strncmp("Hello World", "Hello PHP", 5); // Output: 0 (first 5 chars equal)
?>
10. String Formatting:
<?php
// sprintf() - Format string
$name = "John";
$age = 25;
$formatted = sprintf("Name: %s, Age: %d", $name, $age);
echo $formatted; // Output: Name: John, Age: 25
// number_format() - Format numbers
$number = 1234567.89;
echo number_format($number, 2, ".", ","); // Output: 1,234,567.89
// str_pad() - Pad string to certain length
echo str_pad("5", 3, "0", STR_PAD_LEFT); // Output: 005
// wordwrap() - Wrap text to given number of characters
$longText = "This is a very long string that needs to be wrapped";
echo wordwrap($longText, 20, "<br>");
?>
11. String Reversal and Repetition:
<?php
// strrev() - Reverse string
echo strrev("Hello"); // Output: olleH
// str_repeat() - Repeat string
echo str_repeat("*", 10); // Output: **********
echo str_repeat("Hello ", 3); // Output: Hello Hello Hello
?>
12. HTML and Special Character Handling:
<?php
// htmlspecialchars() - Convert special characters to HTML entities
$text = '<script>alert("XSS")</script>';
echo htmlspecialchars($text);
// Output: <script>alert("XSS")</script>
// htmlentities() - Convert all applicable characters to HTML entities
echo htmlentities("<p>Hello & Welcome</p>");
// Output: <p>Hello & Welcome</p>
// strip_tags() - Remove HTML and PHP tags
$html = "<p>Hello <b>World</b></p>";
echo strip_tags($html); // Output: Hello World
// nl2br() - Insert HTML line breaks before newlines
$text = "Line 1\nLine 2\nLine 3";
echo nl2br($text); // Output: Line 1<br>Line 2<br>Line 3
?>
13. String Parsing:
<?php
// parse_str() - Parse query string into variables
$queryString = "name=John&age=25&city=New York";
parse_str($queryString, $params);
print_r($params);
// Output: Array([name] => John [age] => 25 [city] => New York)
// sscanf() - Parse string according to format
$text = "Serial: 12345";
sscanf($text, "Serial: %d", $serial);
echo $serial; // Output: 12345
?>
Complete String Processing Example:
<?php
// Student data processing example
$studentData = " JOHN DOE | john@example.com | web programming ";
echo "<h3>Original Data:</h3>";
echo htmlspecialchars($studentData) . "<br><br>";
// 1. Trim whitespace
$studentData = trim($studentData);
// 2. Convert to proper case
$studentData = ucwords(strtolower($studentData));
// 3. Split by delimiter
$parts = explode("|", $studentData);
$name = trim($parts[0]);
$email = trim($parts[1]);
$course = trim($parts[2]);
echo "<h3>Processed Data:</h3>";
echo "Name: $name<br>";
echo "Email: " . strtolower($email) . "<br>";
echo "Course: " . ucwords($course) . "<br><br>";
// 4. Validate email
if (strpos($email, "@") !== false && strpos($email, ".") !== false) {
echo "Email format: Valid<br>";
} else {
echo "Email format: Invalid<br>";
}
// 5. Count characters
echo "Name length: " . strlen($name) . " characters<br>";
// 6. Replace course name
$newCourse = str_replace("Web Programming", "CST463", $course);
echo "Course Code: $newCourse<br>";
?>
Output:
Original Data:
JOHN DOE | john@example.com | web programming
Processed Data:
Name: John Doe
Email: john@example.com
Course: Web Programming
Email format: Valid
Name length: 8 characters
Course Code: Cst463
Summary:
PHP provides comprehensive string processing capabilities including case manipulation, searching, replacing, splitting, joining, trimming, and formatting. These functions enable developers to efficiently handle text data, validate user input, format output, and process strings for various applications.
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 16(b) - MARK DISTRIBUTION (Total: 6 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. String Processing Functions β 6 marks β
β - strcmp(), substr(), str_replace() β β
β - strlen() and other string operations β β
β - Examples demonstrating usage β β
β - Various string manipulation techniques β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
Module IV β Module IV
Question 17 (14 marks) β a) With suitable examples, discuss the various steps for establishing I. PHP-MySQL connection with a database II. PHP-MySQL Query Execution (8 marks)
a) With suitable examples, discuss the various steps for establishing I. PHP-MySQL connection with a database II. PHP-MySQL Query Execution (8 marks)
Answer:
PHP-MySQL Integration using PDO (PHP Data Objects)
PDO (PHP Data Objects) is the modern, recommended approach for database interactions in PHP. It provides a consistent interface for accessing different database systems and offers superior security through prepared statements.
I. PHP-MySQL Connection with a Database
Step 1: Install and Configure MySQL Database
Before connecting, ensure MySQL server is running and you have:
- Database name
- Username (typically 'root' for local development)
- Password
- Host (typically 'localhost')
- Port (default: 3306)
Step 2: Create Database and Table
-- Create database
CREATE DATABASE student_portal;
-- Use the database
USE student_portal;
-- Create table
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
phone VARCHAR(15),
course VARCHAR(50),
enrollment_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Step 3: Establish PDO Connection
Syntax:
$pdo = new PDO($dsn, $username, $password, $options);
Complete Connection Example:
<?php
try {
// Database configuration
$host = 'localhost';
$dbname = 'student_portal';
$username = 'root';
$password = '';
// Data Source Name (DSN)
$dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4";
// PDO options for security and error handling
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // Throw exceptions on errors
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // Fetch as associative array
PDO::ATTR_EMULATE_PREPARES => false, // Use real prepared statements
];
// Create PDO instance
$pdo = new PDO($dsn, $username, $password, $options);
echo "Database connected successfully!";
} catch (PDOException $e) {
// Handle connection errors
die("Connection failed: " . $e->getMessage());
}
?>
Explanation:
- DSN (Data Source Name): Specifies database type, host, name, and character encoding
- PDO::ATTR_ERRMODE: Sets error reporting mode to exceptions
- PDO::ATTR_DEFAULT_FETCH_MODE: Defines how data is fetched (associative array)
- PDO::ATTR_EMULATE_PREPARES: Disables emulation for true prepared statements
- try-catch: Handles connection errors gracefully
II. PHP-MySQL Query Execution
Once connected, execute queries using PDO prepared statements for security.
1. INSERT Operation - Adding Data
<?php
try {
// PDO connection (as shown above)
$pdo = new PDO($dsn, $username, $password, $options);
// Prepare SQL with named parameters
$sql = "INSERT INTO students (name, email, phone, course)
VALUES (:name, :email, :phone, :course)";
$stmt = $pdo->prepare($sql);
// Execute with parameter array
$result = $stmt->execute([
'name' => 'John Doe',
'email' => 'john@example.com',
'phone' => '9876543210',
'course' => 'Computer Science'
]);
if ($result) {
echo "Student added successfully!";
echo "New student ID: " . $pdo->lastInsertId();
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
Alternative with Positional Parameters:
<?php
$sql = "INSERT INTO students (name, email, phone, course) VALUES (?, ?, ?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute(['Alice Smith', 'alice@example.com', '9123456789', 'Information Technology']);
?>
2. SELECT Operation - Retrieving Data
Fetch Single Row:
<?php
// Select student by ID
$sql = "SELECT * FROM students WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute(['id' => 1]);
$student = $stmt->fetch(); // Fetch single row
if ($student) {
echo "Name: " . $student['name'] . "<br>";
echo "Email: " . $student['email'] . "<br>";
echo "Course: " . $student['course'];
} else {
echo "Student not found";
}
?>
Fetch Multiple Rows:
<?php
// Select all students
$sql = "SELECT * FROM students ORDER BY name";
$stmt = $pdo->query($sql); // Direct query (no parameters)
$students = $stmt->fetchAll(); // Fetch all rows
echo "<table border='1'>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th><th>Course</th></tr>";
foreach ($students as $student) {
echo "<tr>";
echo "<td>{$student['id']}</td>";
echo "<td>{$student['name']}</td>";
echo "<td>{$student['email']}</td>";
echo "<td>{$student['course']}</td>";
echo "</tr>";
}
echo "</table>";
?>
3. UPDATE Operation - Modifying Data
<?php
// Update student information
$sql = "UPDATE students SET course = :course, phone = :phone WHERE id = :id";
$stmt = $pdo->prepare($sql);
$result = $stmt->execute([
'course' => 'Software Engineering',
'phone' => '9999888877',
'id' => 1
]);
if ($result) {
echo "Student updated successfully!";
echo "Rows affected: " . $stmt->rowCount();
}
?>
4. DELETE Operation - Removing Data
<?php
// Delete student by ID
$sql = "DELETE FROM students WHERE id = :id";
$stmt = $pdo->prepare($sql);
$result = $stmt->execute(['id' => 5]);
if ($result) {
echo "Student deleted successfully!";
echo "Rows deleted: " . $stmt->rowCount();
}
?>
5. Advanced Queries
Search with LIKE:
<?php
$searchTerm = "John";
$sql = "SELECT * FROM students WHERE name LIKE :search";
$stmt = $pdo->prepare($sql);
$stmt->execute(['search' => "%$searchTerm%"]);
$results = $stmt->fetchAll();
?>
Count Records:
<?php
$sql = "SELECT COUNT(*) as total FROM students WHERE course = :course";
$stmt = $pdo->prepare($sql);
$stmt->execute(['course' => 'Computer Science']);
$row = $stmt->fetch();
echo "Total students: " . $row['total'];
?>
Complete CRUD Application Example:
<?php
try {
// 1. Database Connection
$dsn = "mysql:host=localhost;dbname=student_portal;charset=utf8mb4";
$username = "root";
$password = "";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $username, $password, $options);
// 2. CREATE - Insert new student
function addStudent($pdo, $name, $email, $phone, $course) {
$sql = "INSERT INTO students (name, email, phone, course)
VALUES (:name, :email, :phone, :course)";
$stmt = $pdo->prepare($sql);
return $stmt->execute([
'name' => $name,
'email' => $email,
'phone' => $phone,
'course' => $course
]);
}
// 3. READ - Get all students
function getAllStudents($pdo) {
$sql = "SELECT * FROM students ORDER BY id DESC";
$stmt = $pdo->query($sql);
return $stmt->fetchAll();
}
// 4. UPDATE - Update student details
function updateStudent($pdo, $id, $name, $email, $phone, $course) {
$sql = "UPDATE students
SET name = :name, email = :email, phone = :phone, course = :course
WHERE id = :id";
$stmt = $pdo->prepare($sql);
return $stmt->execute([
'name' => $name,
'email' => $email,
'phone' => $phone,
'course' => $course,
'id' => $id
]);
}
// 5. DELETE - Remove student
function deleteStudent($pdo, $id) {
$sql = "DELETE FROM students WHERE id = :id";
$stmt = $pdo->prepare($sql);
return $stmt->execute(['id' => $id]);
}
// Usage examples
addStudent($pdo, "Bob Wilson", "bob@example.com", "9876543210", "Data Science");
$allStudents = getAllStudents($pdo);
foreach ($allStudents as $student) {
echo $student['name'] . " - " . $student['course'] . "<br>";
}
} catch (PDOException $e) {
die("Database Error: " . $e->getMessage());
}
?>
Best Practices:
- Use PDO over mysqli: Modern, secure, database-independent
- Always use prepared statements: Prevents SQL injection
- Handle errors with try-catch: Graceful error management
- Use named parameters: More readable than positional
- Close connections automatically: PDO closes when script ends
- Validate input: Before database operations
- Use transactions: For multiple related operations
Transaction Example:
<?php
try {
$pdo->beginTransaction();
// Multiple operations
$stmt1 = $pdo->prepare("INSERT INTO students (name, email) VALUES (?, ?)");
$stmt1->execute(['Student 1', 'student1@example.com']);
$stmt2 = $pdo->prepare("INSERT INTO enrollments (student_id, course_id) VALUES (?, ?)");
$stmt2->execute([$pdo->lastInsertId(), 101]);
$pdo->commit(); // Commit if all succeed
} catch (Exception $e) {
$pdo->rollBack(); // Rollback on error
echo "Transaction failed: " . $e->getMessage();
}
?>
Summary:
PHP-MySQL integration using PDO involves establishing a connection with proper configuration, then executing queries using prepared statements for security. The CRUD operations (Create, Read, Update, Delete) cover all database interaction needs.
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 17(a) - MARK DISTRIBUTION (Total: 8 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. PHP-MySQL Connection with Database β 4 marks β
β - DSN configuration β β
β - PDO instance creation β β
β - Connection options and error handling β β
β β β
β 2. PHP-MySQL Query Execution β 4 marks β
β - Prepared statements β β
β - Query execution methods β β
β - CRUD operations examples β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
b) Write a PHP form handling program to perform the user registration in any student portal with a minimum of 5 different fields and insert the data into a MySQL table after establishing necessary connections with the DB. (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>Student Portal Registration</title>
</head>
<body>
<h2>Student Registration Portal</h2>
<?php
// Database connection and form processing
if ($_SERVER["REQUEST_METHOD"] == "POST") {
try {
// PDO Database Connection
$dsn = "mysql:host=localhost;dbname=student_portal;charset=utf8mb4";
$username = "root";
$password = "";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $username, $password, $options);
// Sanitize and retrieve form data
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$phone = trim($_POST['phone']);
$course = trim($_POST['course']);
$gender = $_POST['gender'];
$dob = $_POST['dob'];
// Validate inputs
$errors = [];
if (empty($name)) {
$errors[] = "Name is required";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format";
}
if (!preg_match("/^[0-9]{10}$/", $phone)) {
$errors[] = "Phone must be 10 digits";
}
if (empty($course)) {
$errors[] = "Please select a course";
}
if (empty($errors)) {
// Prepare SQL with prepared statement
$sql = "INSERT INTO students (name, email, phone, course, gender, dob)
VALUES (:name, :email, :phone, :course, :gender, :dob)";
$stmt = $pdo->prepare($sql);
// Execute with parameters (prevents SQL injection)
$result = $stmt->execute([
'name' => $name,
'email' => $email,
'phone' => $phone,
'course' => $course,
'gender' => $gender,
'dob' => $dob
]);
if ($result) {
echo "<p style='color: green;'>β Registration successful! Student ID: " . $pdo->lastInsertId() . "</p>";
}
} else {
// Display validation errors
echo "<div style='color: red;'>";
foreach ($errors as $error) {
echo "<p>β $error</p>";
}
echo "</div>";
}
} catch (PDOException $e) {
// Handle database errors
if ($e->getCode() == 23000) {
echo "<p style='color: red;'>β Email already registered!</p>";
} else {
echo "<p style='color: red;'>β Database error: " . $e->getMessage() . "</p>";
}
}
}
?>
<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="email">Email: *</label><br>
<input type="email" id="email" name="email" required><br><br>
<label for="phone">Phone Number: *</label><br>
<input type="tel" id="phone" name="phone" pattern="[0-9]{10}"
placeholder="10-digit number" required><br><br>
<label for="course">Course: *</label><br>
<select id="course" name="course" required>
<option value="">-- Select Course --</option>
<option value="Computer Science">Computer Science</option>
<option value="Information Technology">Information Technology</option>
<option value="Electronics">Electronics</option>
<option value="Mechanical">Mechanical</option>
</select><br><br>
<label>Gender: *</label><br>
<input type="radio" id="male" name="gender" value="Male" required>
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="Female" required>
<label for="female">Female</label><br><br>
<label for="dob">Date of Birth: *</label><br>
<input type="date" id="dob" name="dob" required><br><br>
<button type="submit">Register</button>
<button type="reset">Clear</button>
</form>
</body>
</html>
Database Table Creation:
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
phone VARCHAR(15) NOT NULL,
course VARCHAR(50) NOT NULL,
gender ENUM('Male', 'Female') NOT NULL,
dob DATE NOT NULL,
registration_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Explanation:
1. Form Fields (6 required fields):
- Name (text input)
- Email (email input with validation)
- Phone (tel input with 10-digit pattern)
- Course (select dropdown)
- Gender (radio buttons)
- Date of Birth (date picker)
2. Security Features:
- PDO Prepared Statements: Prevents SQL injection
- Input Sanitization:
trim()removes whitespace - Email Validation:
filter_var()with FILTER_VALIDATE_EMAIL - Phone Validation: Regular expression for 10 digits
- HTML Escaping:
htmlspecialchars()prevents XSS - UNIQUE constraint: Prevents duplicate emails
3. Validation:
- Server-side validation for all fields
- Error messages displayed to user
- HTML5 client-side validation (required, pattern)
4. Error Handling:
- Try-catch for database exceptions
- Duplicate entry detection (email uniqueness)
- User-friendly error messages
5. Features:
- Auto-increment ID
- Timestamp for registration date
- Success message with student ID
- Form validation before database insert
Test Case:
Input:
- Name: John Doe
- Email: john@student.edu
- Phone: 9876543210
- Course: Computer Science
- Gender: Male
- DOB: 2003-05-15
Output: β Registration successful! Student ID: 1
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 17(b) - MARK DISTRIBUTION (Total: 6 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. PHP Form Handling Program β 3 marks β
β - HTML form with 5+ fields β β
β - Form validation and sanitization β β
β - $_POST data processing β β
β β β
β 2. Insert Data into MySQL Table β 3 marks β
β - Database connection establishment β β
β - Prepared statement for INSERT operation β β
β - Successful data insertion with feedback β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
Question 18 (14 marks) β a) Explain the process of form processing in PHP. How do you handle form data, validate inputs, and implement business logic before storing or process...
a) Explain the process of form processing in PHP. How do you handle form data, validate inputs, and implement business logic before storing or processing data in a database? (8 marks)
Answer:
Form Processing in PHP - Complete Workflow
Form processing is a critical aspect of web applications, involving data collection, validation, sanitization, business logic implementation, and storage. PHP provides robust mechanisms for handling forms securely and efficiently.
1. Form Submission Methods
GET Method:
- Data appended to URL as query parameters
- Visible in address bar
- Limited data size (~2KB)
- Use for searches, filtering
- Data accessible via
$_GETsuperglobal
POST Method:
- Data sent in HTTP request body
- Not visible in URL
- No size limit (server-dependent)
- Use for forms, sensitive data
- Data accessible via
$_POSTsuperglobal
Example:
<!-- POST form -->
<form method="POST" action="process.php">
<input type="text" name="username">
<button type="submit">Submit</button>
</form>
<!-- GET form -->
<form method="GET" action="search.php">
<input type="text" name="query">
<button type="submit">Search</button>
</form>
2. Retrieving Form Data
<?php
// Check request method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve POST data
$username = $_POST['username'];
$email = $_POST['email'];
$age = $_POST['age'];
}
// For GET requests
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$searchQuery = $_GET['query'];
}
// Check if specific field exists
if (isset($_POST['submit_button'])) {
// Form was submitted
}
?>
3. Input Validation
Validation ensures data meets requirements before processing.
Types of Validation:
a) Required Field Validation:
<?php
$errors = [];
if (empty($_POST['username'])) {
$errors[] = "Username is required";
}
if (empty($_POST['email'])) {
$errors[] = "Email is required";
}
?>
b) Email Validation:
<?php
$email = $_POST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format";
}
?>
c) Length Validation:
<?php
$password = $_POST['password'];
if (strlen($password) < 8) {
$errors[] = "Password must be at least 8 characters";
}
$username = $_POST['username'];
if (strlen($username) < 3 || strlen($username) > 20) {
$errors[] = "Username must be 3-20 characters";
}
?>
d) Numeric Validation:
<?php
$age = $_POST['age'];
if (!is_numeric($age)) {
$errors[] = "Age must be a number";
}
if ($age < 18 || $age > 100) {
$errors[] = "Age must be between 18 and 100";
}
?>
e) Pattern Matching (Regular Expressions):
<?php
$phone = $_POST['phone'];
// Validate 10-digit phone
if (!preg_match("/^[0-9]{10}$/", $phone)) {
$errors[] = "Phone must be 10 digits";
}
// Validate alphanumeric username
if (!preg_match("/^[a-zA-Z0-9_]+$/", $username)) {
$errors[] = "Username can only contain letters, numbers, and underscore";
}
?>
4. Input Sanitization
Sanitization cleans data to remove harmful content.
<?php
// Remove whitespace
$name = trim($_POST['name']);
// Remove HTML tags
$comment = strip_tags($_POST['comment']);
// Filter email
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
// Escape HTML special characters (prevent XSS)
$userInput = htmlspecialchars($_POST['input'], ENT_QUOTES, 'UTF-8');
// Remove specific characters
$phone = preg_replace("/[^0-9]/", "", $_POST['phone']); // Keep only digits
?>
5. Business Logic Implementation
Business logic applies application-specific rules and transformations.
<?php
// Calculate discount based on purchase amount
function calculateDiscount($amount) {
if ($amount >= 10000) {
return $amount * 0.20; // 20% discount
} elseif ($amount >= 5000) {
return $amount * 0.10; // 10% discount
}
return 0;
}
// Check stock availability
function checkStock($productId, $quantity, $pdo) {
$sql = "SELECT stock FROM products WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute(['id' => $productId]);
$product = $stmt->fetch();
if ($product['stock'] >= $quantity) {
return true;
}
return false;
}
// Hash password
$password = $_POST['password'];
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
// Generate unique ID
$orderId = "ORD" . time() . rand(1000, 9999);
?>
6. Complete Form Processing Example
<?php
// Initialize variables
$errors = [];
$success = false;
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// STEP 1: Retrieve and Sanitize Input
$name = trim($_POST['name']);
$email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
$phone = preg_replace("/[^0-9]/", "", $_POST['phone']);
$password = $_POST['password'];
$confirmPassword = $_POST['confirm_password'];
$age = filter_var($_POST['age'], FILTER_SANITIZE_NUMBER_INT);
// STEP 2: Validate Inputs
// Name validation
if (empty($name)) {
$errors[] = "Name is required";
} elseif (strlen($name) < 3) {
$errors[] = "Name must be at least 3 characters";
}
// Email validation
if (empty($email)) {
$errors[] = "Email is required";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format";
}
// Phone validation
if (empty($phone)) {
$errors[] = "Phone is required";
} elseif (strlen($phone) != 10) {
$errors[] = "Phone must be 10 digits";
}
// Password validation
if (empty($password)) {
$errors[] = "Password is required";
} elseif (strlen($password) < 8) {
$errors[] = "Password must be at least 8 characters";
} elseif ($password !== $confirmPassword) {
$errors[] = "Passwords do not match";
}
// Age validation
if (empty($age)) {
$errors[] = "Age is required";
} elseif ($age < 18) {
$errors[] = "Must be 18 or older";
}
// STEP 3: Business Logic
if (empty($errors)) {
// Hash password
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
// Generate username
$username = strtolower(str_replace(" ", "_", $name)) . rand(100, 999);
// STEP 4: Database Operations
try {
// Database connection
$dsn = "mysql:host=localhost;dbname=userdb;charset=utf8mb4";
$dbUsername = "root";
$dbPassword = "";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];
$pdo = new PDO($dsn, $dbUsername, $dbPassword, $options);
// Check if email already exists
$checkSql = "SELECT COUNT(*) FROM users WHERE email = :email";
$checkStmt = $pdo->prepare($checkSql);
$checkStmt->execute(['email' => $email]);
if ($checkStmt->fetchColumn() > 0) {
$errors[] = "Email already registered";
} else {
// Insert user
$sql = "INSERT INTO users (username, name, email, phone, password, age)
VALUES (:username, :name, :email, :phone, :password, :age)";
$stmt = $pdo->prepare($sql);
$result = $stmt->execute([
'username' => $username,
'name' => $name,
'email' => $email,
'phone' => $phone,
'password' => $hashedPassword,
'age' => $age
]);
if ($result) {
$success = true;
$userId = $pdo->lastInsertId();
// Send welcome email (business logic)
// sendWelcomeEmail($email, $name);
// Redirect to success page
// header("Location: success.php?id=" . $userId);
// exit;
}
}
} catch (PDOException $e) {
$errors[] = "Database error: " . $e->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Registration</title>
</head>
<body>
<h2>User Registration Form</h2>
<?php if ($success): ?>
<p style="color: green;">β Registration successful! Your username is: <?php echo htmlspecialchars($username); ?></p>
<?php endif; ?>
<?php if (!empty($errors)): ?>
<div style="color: red;">
<h3>Please correct the following errors:</h3>
<ul>
<?php foreach ($errors as $error): ?>
<li><?php echo htmlspecialchars($error); ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ''; ?>"><br><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email" value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>"><br><br>
<label for="phone">Phone:</label><br>
<input type="tel" id="phone" name="phone" value="<?php echo isset($_POST['phone']) ? htmlspecialchars($_POST['phone']) : ''; ?>"><br><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<label for="confirm_password">Confirm Password:</label><br>
<input type="password" id="confirm_password" name="confirm_password"><br><br>
<label for="age">Age:</label><br>
<input type="number" id="age" name="age" value="<?php echo isset($_POST['age']) ? htmlspecialchars($_POST['age']) : ''; ?>"><br><br>
<button type="submit">Register</button>
</form>
</body>
</html>
Form Processing Best Practices:
- Always validate on server-side: Client-side validation can be bypassed
- Sanitize all inputs: Prevent XSS and injection attacks
- Use prepared statements: Prevent SQL injection
- Hash passwords: Never store plain text passwords
- Implement CSRF protection: Use tokens for form submissions
- Provide clear error messages: Help users correct mistakes
- Preserve form data on error: Repopulate fields after validation failure
- Use HTTPS: Encrypt data transmission
- Limit file uploads: Validate type and size
- Log errors securely: Don't expose sensitive information to users
Summary:
Form processing in PHP involves retrieving data from $_POST/$_GET, validating inputs, sanitizing to prevent attacks, implementing business logic, and securely storing in database using prepared statements. Proper error handling and user feedback are essential for good user experience.
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 18(a) - MARK DISTRIBUTION (Total: 8 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. Form Processing in PHP β 4 marks β
β - Handling form data ($_POST/$_GET) β β
β - Form validation techniques β β
β - Input sanitization methods β β
β β β
β 2. Implement Business Logic β 4 marks β
β - Business rules validation β β
β - Data processing before storage β β
β - Database insertion with prepared stmt β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
b) Explain how dynamic content is fetched from the database and displayed on a webpage. (6 marks)
Answer:
Dynamic Content Generation from Database
Dynamic web pages display content that changes based on database data, user interactions, or real-time information. PHP fetches data from MySQL and generates HTML dynamically.
Process Overview:
- User requests webpage
- PHP connects to MySQL database
- PHP executes SQL query
- Database returns result set
- PHP processes data
- PHP generates HTML with data
- Browser displays dynamic content
Example 1: Displaying Student List
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student List</title>
<style>
table { border-collapse: collapse; width: 80%; margin: 20px auto; }
th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
th { background-color: #4CAF50; color: white; }
tr:nth-child(even) { background-color: #f2f2f2; }
tr:hover { background-color: #ddd; }
</style>
</head>
<body>
<h2 style="text-align: center;">Student Database</h2>
<?php
try {
// Database connection
$pdo = new PDO("mysql:host=localhost;dbname=student_portal", "root", "", [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
// Fetch data from database
$sql = "SELECT id, name, email, course, enrollment_date FROM students ORDER BY id DESC";
$stmt = $pdo->query($sql);
$students = $stmt->fetchAll();
if (count($students) > 0) {
echo "<table>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th><th>Course</th><th>Enrolled</th></tr>";
// Loop through results and generate HTML
foreach ($students as $student) {
echo "<tr>";
echo "<td>" . htmlspecialchars($student['id']) . "</td>";
echo "<td>" . htmlspecialchars($student['name']) . "</td>";
echo "<td>" . htmlspecialchars($student['email']) . "</td>";
echo "<td>" . htmlspecialchars($student['course']) . "</td>";
echo "<td>" . date('M d, Y', strtotime($student['enrollment_date'])) . "</td>";
echo "</tr>";
}
echo "</table>";
echo "<p style='text-align: center;'>Total Students: " . count($students) . "</p>";
} else {
echo "<p style='text-align: center;'>No students found in database.</p>";
}
} catch (PDOException $e) {
echo "<p style='color: red; text-align: center;'>Error fetching data: " . $e->getMessage() . "</p>";
}
?>
</body>
</html>
Example 2: Student Details Page (Single Record)
<?php
// Get student ID from URL parameter
$studentId = isset($_GET['id']) ? intval($_GET['id']) : 0;
try {
$pdo = new PDO("mysql:host=localhost;dbname=student_portal", "root", "", [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
// Fetch specific student
$sql = "SELECT * FROM students WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute(['id' => $studentId]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);
if ($student) {
?>
<!DOCTYPE html>
<html>
<head>
<title>Student Profile</title>
</head>
<body>
<h2>Student Profile</h2>
<div style="border: 1px solid #ccc; padding: 20px; width: 500px;">
<p><strong>ID:</strong> <?php echo htmlspecialchars($student['id']); ?></p>
<p><strong>Name:</strong> <?php echo htmlspecialchars($student['name']); ?></p>
<p><strong>Email:</strong> <?php echo htmlspecialchars($student['email']); ?></p>
<p><strong>Phone:</strong> <?php echo htmlspecialchars($student['phone']); ?></p>
<p><strong>Course:</strong> <?php echo htmlspecialchars($student['course']); ?></p>
<p><strong>Enrolled:</strong> <?php echo date('F j, Y', strtotime($student['enrollment_date'])); ?></p>
</div>
<br>
<a href="students.php">β Back to Student List</a>
</body>
</html>
<?php
} else {
echo "Student not found!";
}
} catch (PDOException $e) {
echo "Database error: " . $e->getMessage();
}
?>
Example 3: Search and Filter
<!DOCTYPE html>
<html>
<head>
<title>Search Students</title>
</head>
<body>
<h2>Search Students</h2>
<!-- Search Form -->
<form method="GET" action="">
<input type="text" name="search" placeholder="Search by name or course"
value="<?php echo isset($_GET['search']) ? htmlspecialchars($_GET['search']) : ''; ?>">
<button type="submit">Search</button>
<a href="search.php">Clear</a>
</form>
<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=student_portal", "root", "");
if (isset($_GET['search']) && !empty($_GET['search'])) {
$searchTerm = "%" . $_GET['search'] . "%";
$sql = "SELECT * FROM students
WHERE name LIKE :search OR course LIKE :search
ORDER BY name";
$stmt = $pdo->prepare($sql);
$stmt->execute(['search' => $searchTerm]);
} else {
$sql = "SELECT * FROM students ORDER BY name";
$stmt = $pdo->query($sql);
}
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<h3>Results: " . count($results) . " student(s) found</h3>";
if (count($results) > 0) {
echo "<ul>";
foreach ($results as $student) {
echo "<li>";
echo "<strong>" . htmlspecialchars($student['name']) . "</strong> - ";
echo htmlspecialchars($student['course']) . " ";
echo "(<a href='details.php?id=" . $student['id'] . "'>View Details</a>)";
echo "</li>";
}
echo "</ul>";
} else {
echo "<p>No students match your search.</p>";
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
</body>
</html>
Example 4: Pagination
<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=student_portal", "root", "");
// Pagination settings
$recordsPerPage = 10;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$offset = ($page - 1) * $recordsPerPage;
// Get total records
$totalSql = "SELECT COUNT(*) FROM students";
$totalRecords = $pdo->query($totalSql)->fetchColumn();
$totalPages = ceil($totalRecords / $recordsPerPage);
// Fetch paginated data
$sql = "SELECT * FROM students LIMIT :limit OFFSET :offset";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':limit', $recordsPerPage, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Display results
echo "<h3>Page $page of $totalPages</h3>";
foreach ($students as $student) {
echo "<p>" . htmlspecialchars($student['name']) . " - " . htmlspecialchars($student['course']) . "</p>";
}
// Pagination links
echo "<div>";
if ($page > 1) {
echo "<a href='?page=" . ($page - 1) . "'>β Previous</a> ";
}
for ($i = 1; $i <= $totalPages; $i++) {
if ($i == $page) {
echo "<strong>$i</strong> ";
} else {
echo "<a href='?page=$i'>$i</a> ";
}
}
if ($page < $totalPages) {
echo "<a href='?page=" . ($page + 1) . "'>Next β</a>";
}
echo "</div>";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
Key Techniques:
- PDO Query:
$pdo->query($sql)for static queries - Prepared Statements:
$pdo->prepare()for dynamic/user data - Fetch Methods:
fetch()- Single rowfetchAll()- All rowsfetchColumn()- Single value
- Data Processing: Loops to generate HTML
- HTML Escaping:
htmlspecialchars()prevents XSS - Date Formatting:
date()andstrtotime() - Conditional Display: Show/hide based on data availability
Summary:
Dynamic content is fetched by connecting to MySQL via PDO, executing SQL queries, retrieving result sets, processing data in PHP loops, and generating HTML dynamically. The content updates automatically as database changes, providing real-time information to users.
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 18(b) - MARK DISTRIBUTION (Total: 6 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. Database Connection β 1 mark β
β β β
β 2. Query Execution β 2 marks β
β β β
β 3. Processing Results β 1 mark β
β β β
β 4. Displaying Data β 1 mark β
β β β
β 5. Closing Connection β 1 mark β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
Module V β Module V
Question 19 (14 marks) β a) Enumerate the data types in JSON. Illustrate the document definition of a 'Student document' using JSON Schema. (8 marks)
a) Enumerate the data types in JSON. Illustrate the document definition of a 'Student document' using JSON Schema. (8 marks)
Answer:
JSON (JavaScript Object Notation)
JSON is a lightweight, text-based data interchange format that's easy for humans to read and write, and easy for machines to parse and generate.
Data Types in JSON:
JSON supports six fundamental data types:
1. String
- Text enclosed in double quotes
- Supports Unicode characters
- Escape sequences:
\",\\,\/,\b,\f,\n,\r,\t
{
"name": "John Doe",
"address": "123 Main St, New York",
"message": "Hello\nWorld"
}
2. Number
- Integer or floating-point
- No quotes
- Can be positive, negative, or exponential
{
"age": 25,
"price": 99.99,
"temperature": -15.5,
"scientific": 2.5e6,
"negative_exponent": 1.23e-4
}
3. Boolean
- Only two values:
trueorfalse(lowercase) - No quotes
{
"isActive": true,
"hasGraduated": false,
"verified": true
}
4. Null
- Represents absence of value
- Keyword:
null(lowercase)
{
"middleName": null,
"previousAddress": null
}
5. Object
- Unordered collection of key-value pairs
- Enclosed in curly braces
{} - Keys must be strings
- Values can be any JSON data type
{
"student": {
"name": "Alice",
"age": 22,
"contact": {
"email": "alice@example.com",
"phone": "9876543210"
}
}
}
6. Array
- Ordered list of values
- Enclosed in square brackets
[] - Values can be any JSON data type
- Values can be of different types
{
"courses": ["Mathematics", "Physics", "Chemistry"],
"marks": [85, 92, 78, 88],
"mixedArray": ["text", 123, true, null, {"key": "value"}]
}
Student Document using JSON Schema
JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. It defines the structure, data types, and validation rules.
Student Document JSON Schema:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.com/student.schema.json",
"title": "Student",
"description": "A student record in the university system",
"type": "object",
"required": ["studentId", "name", "email", "program"],
"properties": {
"studentId": {
"description": "Unique student identification number",
"type": "string",
"pattern": "^STU[0-9]{6}$",
"examples": ["STU123456"]
},
"name": {
"description": "Full name of the student",
"type": "object",
"required": ["firstName", "lastName"],
"properties": {
"firstName": {
"type": "string",
"minLength": 1,
"maxLength": 50
},
"middleName": {
"type": "string",
"maxLength": 50
},
"lastName": {
"type": "string",
"minLength": 1,
"maxLength": 50
}
}
},
"dateOfBirth": {
"description": "Student's date of birth",
"type": "string",
"format": "date",
"examples": ["2003-05-15"]
},
"email": {
"description": "Student's email address",
"type": "string",
"format": "email",
"examples": ["student@university.edu"]
},
"phone": {
"description": "Contact phone number",
"type": "string",
"pattern": "^[0-9]{10}$"
},
"program": {
"description": "Academic program",
"type": "string",
"enum": ["Computer Science", "Information Technology", "Electronics", "Mechanical"]
},
"year": {
"description": "Current year of study",
"type": "integer",
"minimum": 1,
"maximum": 4
},
"gpa": {
"description": "Grade Point Average",
"type": "number",
"minimum": 0.0,
"maximum": 10.0
},
"courses": {
"description": "List of enrolled courses",
"type": "array",
"items": {
"type": "object",
"required": ["courseCode", "courseName", "credits"],
"properties": {
"courseCode": {
"type": "string",
"pattern": "^[A-Z]{3}[0-9]{3}$"
},
"courseName": {
"type": "string"
},
"credits": {
"type": "integer",
"minimum": 1,
"maximum": 6
},
"grade": {
"type": "string",
"enum": ["A+", "A", "B", "C", "D", "F"]
}
}
},
"minItems": 1,
"maxItems": 10
},
"address": {
"description": "Student's address",
"type": "object",
"properties": {
"street": {"type": "string"},
"city": {"type": "string"},
"state": {"type": "string"},
"zipCode": {"type": "string", "pattern": "^[0-9]{6}$"},
"country": {"type": "string", "default": "India"}
}
},
"isActive": {
"description": "Whether the student is currently enrolled",
"type": "boolean",
"default": true
},
"scholarships": {
"description": "List of scholarships awarded",
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string"},
"amount": {"type": "number", "minimum": 0},
"year": {"type": "integer"}
}
}
},
"emergencyContact": {
"description": "Emergency contact information",
"type": "object",
"required": ["name", "phone"],
"properties": {
"name": {"type": "string"},
"relationship": {"type": "string"},
"phone": {"type": "string", "pattern": "^[0-9]{10}$"}
}
}
}
}
Valid Student Document Instance:
{
"studentId": "STU123456",
"name": {
"firstName": "Rajesh",
"middleName": "Kumar",
"lastName": "Sharma"
},
"dateOfBirth": "2003-08-15",
"email": "rajesh.sharma@university.edu",
"phone": "9876543210",
"program": "Computer Science",
"year": 3,
"gpa": 8.5,
"courses": [
{
"courseCode": "CST463",
"courseName": "Web Programming",
"credits": 3,
"grade": "A"
},
{
"courseCode": "CST401",
"courseName": "Database Management",
"credits": 4,
"grade": "A+"
},
{
"courseCode": "CST301",
"courseName": "Operating Systems",
"credits": 4,
"grade": "B"
}
],
"address": {
"street": "123 MG Road",
"city": "Bangalore",
"state": "Karnataka",
"zipCode": "560001",
"country": "India"
},
"isActive": true,
"scholarships": [
{
"name": "Merit Scholarship",
"amount": 50000,
"year": 2024
}
],
"emergencyContact": {
"name": "Suresh Sharma",
"relationship": "Father",
"phone": "9123456789"
}
}
JSON Schema Key Components:
- $schema: Indicates which JSON Schema version is being used
- $id: Unique identifier for the schema
- title: Human-readable title
- type: Data type (object, array, string, number, boolean, null)
- required: Array of mandatory properties
- properties: Defines each property's schema
- pattern: Regular expression for string validation
- enum: Restricts values to specific set
- minimum/maximum: Numeric range constraints
- minLength/maxLength: String length constraints
- format: Common data formats (email, date, time, etc.)
- default: Default value if not provided
Benefits of JSON Schema:
- Validates data structure and types
- Documents expected JSON format
- Provides clear API contracts
- Enables automated testing
- Reduces errors in data exchange
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 19(a) - MARK DISTRIBUTION (Total: 8 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. Data Types in JSON β 4 marks β
β - String, Number, Boolean, Null β β
β - Object and Array types β β
β - Examples of each data type β β
β β β
β 2. Student Document JSON Schema β 4 marks β
β - Schema structure and components β β
β - Required fields and properties β β
β - Validation rules and constraints β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
b) Discuss the role of Resource Controllers in Laravel. (6 marks)
Answer:
Resource Controllers in Laravel
Resource Controllers provide a convenient way to create controllers that handle typical CRUD (Create, Read, Update, Delete) operations for a resource. Laravel follows RESTful conventions, making it easy to build standard web applications.
What are Resource Controllers?
A Resource Controller is a controller that implements all standard RESTful actions for a given resource (like users, posts, products) in predefined methods. Instead of writing each route and method manually, Laravel generates them automatically.
Creating a Resource Controller:
# Create resource controller
php artisan make:controller StudentController --resource
# Create resource controller with model binding
php artisan make:controller StudentController --resource --model=Student
Standard Resource Controller Methods:
Laravel Resource Controllers include seven standard methods:
| HTTP Verb | URI | Action | Route Name | Purpose |
|---|---|---|---|---|
| GET | /students | index | students.index | Display all students |
| GET | /students/create | create | students.create | Show form to create new student |
| POST | /students | store | students.store | Store new student in database |
| GET | /students/{id} | show | students.show | Display specific student |
| GET | /students/{id}/edit | edit | students.edit | Show form to edit student |
| PUT/PATCH | /students/{id} | update | students.update | Update specific student |
| DELETE | /students/{id} | destroy | students.destroy | Delete specific student |
Resource Controller Example:
<?php
namespace App\Http\Controllers;
use App\Models\Student;
use Illuminate\Http\Request;
class StudentController extends Controller
{
/**
* Display a listing of the resource.
* GET /students
*/
public function index()
{
$students = Student::all();
return view('students.index', compact('students'));
}
/**
* Show the form for creating a new resource.
* GET /students/create
*/
public function create()
{
return view('students.create');
}
/**
* Store a newly created resource in storage.
* POST /students
*/
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|max:100',
'email' => 'required|email|unique:students',
'course' => 'required'
]);
$student = Student::create($validated);
return redirect()->route('students.index')
->with('success', 'Student created successfully');
}
/**
* Display the specified resource.
* GET /students/{id}
*/
public function show(Student $student)
{
return view('students.show', compact('student'));
}
/**
* Show the form for editing the specified resource.
* GET /students/{id}/edit
*/
public function edit(Student $student)
{
return view('students.edit', compact('student'));
}
/**
* Update the specified resource in storage.
* PUT/PATCH /students/{id}
*/
public function update(Request $request, Student $student)
{
$validated = $request->validate([
'name' => 'required|max:100',
'email' => 'required|email|unique:students,email,' . $student->id,
'course' => 'required'
]);
$student->update($validated);
return redirect()->route('students.index')
->with('success', 'Student updated successfully');
}
/**
* Remove the specified resource from storage.
* DELETE /students/{id}
*/
public function destroy(Student $student)
{
$student->delete();
return redirect()->route('students.index')
->with('success', 'Student deleted successfully');
}
}
Registering Resource Routes:
In routes/web.php:
<?php
use App\Http\Controllers\StudentController;
// Single line creates all 7 RESTful routes
Route::resource('students', StudentController::class);
// This is equivalent to:
/*
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/{student}', [StudentController::class, 'show'])->name('students.show');
Route::get('/students/{student}/edit', [StudentController::class, 'edit'])->name('students.edit');
Route::put('/students/{student}', [StudentController::class, 'update'])->name('students.update');
Route::delete('/students/{student}', [StudentController::class, 'destroy'])->name('students.destroy');
*/
Partial Resource Routes:
Specify only certain actions:
// Only show these routes
Route::resource('students', StudentController::class)->only([
'index', 'show', 'create', 'store'
]);
// Exclude these routes
Route::resource('students', StudentController::class)->except([
'destroy'
]);
API Resource Controllers:
For API applications (JSON responses):
php artisan make:controller API/StudentController --api
This creates a controller without create and edit methods (not needed for APIs):
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use App\Models\Student;
use Illuminate\Http\Request;
class StudentController extends Controller
{
public function index()
{
return Student::all();
}
public function store(Request $request)
{
$student = Student::create($request->all());
return response()->json($student, 201);
}
public function show(Student $student)
{
return response()->json($student);
}
public function update(Request $request, Student $student)
{
$student->update($request->all());
return response()->json($student);
}
public function destroy(Student $student)
{
$student->delete();
return response()->json(null, 204);
}
}
API Resource Route:
Route::apiResource('students', StudentController::class);
Route Model Binding:
Laravel automatically injects model instances based on route parameters:
// Instead of:
public function show($id)
{
$student = Student::findOrFail($id);
return view('students.show', compact('student'));
}
// Use automatic injection:
public function show(Student $student)
{
return view('students.show', compact('student'));
}
View Resource Routes:
# List all routes
php artisan route:list
# Filter by resource
php artisan route:list --name=students
Nested Resource Controllers:
For related resources (e.g., student courses):
// routes/web.php
Route::resource('students.courses', CourseController::class);
// Generates routes like:
// GET /students/{student}/courses
// POST /students/{student}/courses
// etc.
// Controller method
public function index(Student $student)
{
$courses = $student->courses;
return view('courses.index', compact('student', 'courses'));
}
Middleware on Resource Routes:
Route::resource('students', StudentController::class)
->middleware('auth');
// Apply to specific actions
Route::resource('students', StudentController::class)
->only(['index', 'show'])
->middleware('guest');
Advantages of Resource Controllers:
- Convention over Configuration: Follows RESTful standards
- Rapid Development: One command creates all CRUD operations
- Consistency: Standardized method names across application
- Maintainability: Easy to understand and modify
- Route Organization: Cleaner routes file
- Automatic Model Binding: Less boilerplate code
- Named Routes: Easy linking with
route('students.show', $student)
Disadvantages:
- Less Flexibility: Must follow predefined structure
- Unused Routes: May generate routes you don't need (use
onlyorexcept) - Learning Curve: Requires understanding of REST conventions
Summary:
Resource Controllers in Laravel provide a standardized, efficient way to handle CRUD operations following RESTful conventions. They automatically generate routes and controller methods, reducing boilerplate code while maintaining consistency and best practices across the application.
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 19(b) - MARK DISTRIBUTION (Total: 6 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. Controllers Introduction β 2 marks β
β - What are controllers in Laravel β β
β - Purpose and basic functionality β β
β β β
β 2. Role of Resource Controllers in CRUD β 4 marks β
β - RESTful routing conventions β β
β - Standard CRUD method implementation β β
β - Examples of resource controller usage β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
Question 20 (14 marks) β a) Explain the Laravel MVC framework with the help of a neat diagram. Include an example of how data flows through each component in the MVC structure...
a) Explain the Laravel MVC framework with the help of a neat diagram. Include an example of how data flows through each component in the MVC structure. (8 marks)
Answer:
Laravel MVC Framework
MVC (Model-View-Controller) is a software architectural pattern that separates application logic into three interconnected components. Laravel implements MVC to promote organized, maintainable, and scalable web applications.
MVC Components:
1. Model (M):
- Represents data and business logic
- Interacts with database
- Handles data validation
- Located in
app/Models/
2. View (V):
- Presents data to users
- HTML templates (Blade in Laravel)
- No business logic
- Located in
resources/views/
3. Controller (C):
- Handles user requests
- Processes input
- Coordinates Model and View
- Located in
app/Http/Controllers/
Laravel MVC Data Flow Diagram:
ββββββββββββ
β User/ β
β Browser β
ββββββ¬ββββββ
β 1. HTTP Request
βΌ
ββββββββββββββββββββ
β Routes β (web.php / api.php)
β (Entry Point) β
ββββββ¬ββββββββββββββ
β 2. Route to Controller
βΌ
ββββββββββββββββββββ
β CONTROLLER β (StudentController)
β βββββββββββββ β
β - Receives Req β
β - Validates Data β
β - Calls Model β
β - Returns View β
βββββ¬βββββββ¬ββββββββ
β β
β 3. β 5. Data
βCall βfrom
βModel βModel
βΌ βΌ
ββββββββββββββ ββββββββββββββ
β MODEL βββββΊβ DATABASE β
β βββββββββββ β (MySQL) β
β - Business β 4. β β
β Logic βQueryβ β
β - Data β β β
β Rules β β β
ββββββββββββββ ββββββββββββββ
β
β 6. Pass Data
βΌ
ββββββββββββββββββββ
β VIEW β (Blade Template)
β ββββββββββββββ β
β - Display Data β
β - HTML/CSS β
β - User Interface β
ββββββ¬ββββββββββββββ
β 7. HTML Response
βΌ
ββββββββββββ
β User/ β
β Browser β
ββββββββββββ
Detailed Data Flow Steps:
Step 1: User Request
User visits: http://example.com/students
Browser sends HTTP GET request
Step 2: Routing
// routes/web.php
Route::get('/students', [StudentController::class, 'index']);
Step 3: Controller Action
// app/Http/Controllers/StudentController.php
<?php
namespace App\Http\Controllers;
use App\Models\Student;
use Illuminate\Http\Request;
class StudentController extends Controller
{
public function index()
{
// Call Model to fetch data
$students = Student::all();
// Pass data to View
return view('students.index', compact('students'));
}
}
?>
Step 4: Model Interaction
// app/Models/Student.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $table = 'students';
protected $fillable = ['name', 'email', 'course', 'phone'];
// Business logic
public function getFullNameAttribute()
{
return ucwords($this->name);
}
// Relationships
public function courses()
{
return $this->belongsToMany(Course::class);
}
}
?>
Step 5: View Rendering
<!-- resources/views/students/index.blade.php -->
<!DOCTYPE html>
<html>
<head>
<title>Student List</title>
</head>
<body>
<h1>Student Directory</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Course</th>
</tr>
</thead>
<tbody>
@foreach($students as $student)
<tr>
<td>{{ $student->id }}</td>
<td>{{ $student->full_name }}</td>
<td>{{ $student->email }}</td>
<td>{{ $student->course }}</td>
</tr>
@endforeach
</tbody>
</table>
</body>
</html>
Step 6: Response
Laravel compiles Blade template to HTML
Sends HTTP response to browser
Browser renders HTML
Complete Example: Student CRUD
1. Migration (Database Schema):
<?php
// database/migrations/xxxx_create_students_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('phone');
$table->string('course');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('students');
}
};
?>
2. Model:
<?php
// app/Models/Student.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
use HasFactory;
protected $fillable = ['name', 'email', 'phone', 'course'];
// Accessor
public function getFormattedPhoneAttribute()
{
return '+91-' . $this->phone;
}
// Mutator
public function setNameAttribute($value)
{
$this->attributes['name'] = ucwords(strtolower($value));
}
}
?>
3. Controller:
<?php
// 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();
return view('students.index', compact('students'));
}
public function create()
{
return view('students.create');
}
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|max:100',
'email' => 'required|email|unique:students',
'phone' => 'required|digits:10',
'course' => 'required'
]);
Student::create($validated);
return redirect()->route('students.index')
->with('success', 'Student added successfully!');
}
public function show(Student $student)
{
return view('students.show', compact('student'));
}
public function edit(Student $student)
{
return view('students.edit', compact('student'));
}
public function update(Request $request, Student $student)
{
$validated = $request->validate([
'name' => 'required|max:100',
'email' => 'required|email|unique:students,email,' . $student->id,
'phone' => 'required|digits:10',
'course' => 'required'
]);
$student->update($validated);
return redirect()->route('students.index')
->with('success', 'Student updated successfully!');
}
public function destroy(Student $student)
{
$student->delete();
return redirect()->route('students.index')
->with('success', 'Student deleted successfully!');
}
}
?>
4. Routes:
<?php
// routes/web.php
use App\Http\Controllers\StudentController;
Route::resource('students', StudentController::class);
?>
5. Views:
Index View (List):
{{-- resources/views/students/index.blade.php --}}
@extends('layouts.app')
@section('content')
<div class="container">
<h1>Student Directory</h1>
@if(session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
<a href="{{ route('students.create') }}" class="btn btn-primary">Add New Student</a>
<table class="table mt-3">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Course</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@forelse($students as $student)
<tr>
<td>{{ $student->id }}</td>
<td>{{ $student->name }}</td>
<td>{{ $student->email }}</td>
<td>{{ $student->formatted_phone }}</td>
<td>{{ $student->course }}</td>
<td>
<a href="{{ route('students.show', $student) }}">View</a> |
<a href="{{ route('students.edit', $student) }}">Edit</a> |
<form action="{{ route('students.destroy', $student) }}" method="POST" style="display:inline">
@csrf
@method('DELETE')
<button type="submit" onclick="return confirm('Are you sure?')">Delete</button>
</form>
</td>
</tr>
@empty
<tr>
<td colspan="6">No students found.</td>
</tr>
@endforelse
</tbody>
</table>
</div>
@endsection
Create View (Form):
{{-- resources/views/students/create.blade.php --}}
@extends('layouts.app')
@section('content')
<div class="container">
<h1>Add New Student</h1>
@if($errors->any())
<div class="alert alert-danger">
<ul>
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="{{ route('students.store') }}" method="POST">
@csrf
<div class="form-group">
<label>Name:</label>
<input type="text" name="name" class="form-control" value="{{ old('name') }}" required>
</div>
<div class="form-group">
<label>Email:</label>
<input type="email" name="email" class="form-control" value="{{ old('email') }}" required>
</div>
<div class="form-group">
<label>Phone:</label>
<input type="tel" name="phone" class="form-control" value="{{ old('phone') }}" required>
</div>
<div class="form-group">
<label>Course:</label>
<select name="course" class="form-control" required>
<option value="">Select Course</option>
<option value="Computer Science">Computer Science</option>
<option value="Information Technology">Information Technology</option>
<option value="Electronics">Electronics</option>
</select>
</div>
<button type="submit" class="btn btn-success">Save</button>
<a href="{{ route('students.index') }}" class="btn btn-secondary">Cancel</a>
</form>
</div>
@endsection
Benefits of Laravel MVC:
- Separation of Concerns: Each component has distinct responsibility
- Maintainability: Changes in one layer don't affect others
- Testability: Each component can be tested independently
- Reusability: Models and Views can be reused
- Parallel Development: Different developers can work on M, V, C simultaneously
- Scalability: Easy to extend and modify
Summary:
Laravel MVC separates application into Model (data/business logic), View (presentation), and Controller (request handling). Data flows from user request through routes to controller, which interacts with model to fetch/manipulate data, then passes it to view for display. This architecture ensures organized, maintainable, and scalable web applications.
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 20(a) - MARK DISTRIBUTION (Total: 8 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. Laravel MVC Framework Diagram β 4 marks β
β - Model, View, Controller components β β
β - Relationships and connections β β
β - Visual representation of architecture β β
β β β
β 2. Data Flow Example β 4 marks β
β - Request flow through components β β
β - Practical example demonstration β β
β - Complete data lifecycle explanation β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
b) Explain the functionality of JSON.parse() and JSON.stringify() in JavaScript. (6 marks)
Answer:
JSON.parse() and JSON.stringify() in JavaScript
These two methods enable conversion between JSON strings and JavaScript objects, facilitating data exchange between client and server.
1. JSON.stringify()
Purpose: Converts JavaScript objects/values into JSON string format
Syntax:
JSON.stringify(value, replacer, space)
Parameters:
value: The value to convert (required)replacer: Function or array to filter properties (optional)space: Indentation for pretty-printing (optional)
Basic Usage:
// Convert object to JSON string
const student = {
name: "John Doe",
age: 20,
course: "Computer Science",
marks: [85, 92, 78]
};
const jsonString = JSON.stringify(student);
console.log(jsonString);
// Output: {"name":"John Doe","age":20,"course":"Computer Science","marks":[85,92,78]}
// Convert array to JSON string
const courses = ["Math", "Physics", "Chemistry"];
const jsonArray = JSON.stringify(courses);
console.log(jsonArray);
// Output: ["Math","Physics","Chemistry"]
// Convert primitive values
console.log(JSON.stringify(42)); // "42"
console.log(JSON.stringify("Hello")); // ""Hello""
console.log(JSON.stringify(true)); // "true"
console.log(JSON.stringify(null)); // "null"
Pretty Printing (Indentation):
const student = {
name: "Alice",
age: 22,
courses: ["CST463", "CST401"]
};
// Pretty print with 2-space indentation
const formatted = JSON.stringify(student, null, 2);
console.log(formatted);
/* Output:
{
"name": "Alice",
"age": 22,
"courses": [
"CST463",
"CST401"
]
}
*/
// Using tab indentation
const tabFormatted = JSON.stringify(student, null, '\t');
Using Replacer Function:
const user = {
username: "john123",
password: "secret",
email: "john@example.com",
age: 25
};
// Filter out password field
const filtered = JSON.stringify(user, (key, value) => {
if (key === "password") {
return undefined; // Exclude this property
}
return value;
});
console.log(filtered);
// Output: {"username":"john123","email":"john@example.com","age":25}
// Include only specific properties
const limited = JSON.stringify(user, ["username", "email"]);
console.log(limited);
// Output: {"username":"john123","email":"john@example.com"}
Handling Special Cases:
const data = {
date: new Date(),
regex: /test/i,
func: function() { return "hello"; },
undef: undefined,
symbol: Symbol("id"),
number: 123,
nan: NaN,
infinity: Infinity
};
console.log(JSON.stringify(data));
/* Output:
{
"date":"2025-01-18T10:30:00.000Z", // Date converted to ISO string
"number":123,
"nan":null, // NaN becomes null
"infinity":null // Infinity becomes null
}
Note: functions, undefined, symbols are omitted
*/
2. JSON.parse()
Purpose: Converts JSON string into JavaScript object/value
Syntax:
JSON.parse(text, reviver)
Parameters:
text: JSON string to parse (required)reviver: Function to transform results (optional)
Basic Usage:
// Parse JSON string to object
const jsonString = '{"name":"John","age":25,"enrolled":true}';
const student = JSON.parse(jsonString);
console.log(student.name); // John
console.log(student.age); // 25
console.log(student.enrolled); // true
console.log(typeof student); // object
// Parse JSON array
const jsonArray = '["Math","Physics","Chemistry"]';
const courses = JSON.parse(jsonArray);
console.log(courses[0]); // Math
console.log(courses.length); // 3
// Parse primitive values
console.log(JSON.parse('42')); // 42
console.log(JSON.parse('"Hello"')); // Hello
console.log(JSON.parse('true')); // true
console.log(JSON.parse('null')); // null
Error Handling:
try {
// Invalid JSON (missing quotes around property names)
const invalid = '{name: "John"}';
const parsed = JSON.parse(invalid);
} catch (error) {
console.error("JSON Parse Error:", error.message);
// Output: Unexpected token n in JSON at position 1
}
// Always use try-catch for user input
function safeJSONParse(str) {
try {
return JSON.parse(str);
} catch (e) {
console.error("Invalid JSON:", e);
return null;
}
}
Using Reviver Function:
// Transform specific values during parsing
const jsonString = '{"name":"John","birthDate":"2003-05-15","salary":"50000"}';
const student = JSON.parse(jsonString, (key, value) => {
// Convert birthDate string to Date object
if (key === "birthDate") {
return new Date(value);
}
// Convert salary to number
if (key === "salary") {
return parseFloat(value);
}
return value;
});
console.log(student.birthDate instanceof Date); // true
console.log(typeof student.salary); // number
Real-World Use Cases:
1. Local Storage:
// Save object to localStorage
const user = {username: "john", preferences: {theme: "dark"}};
localStorage.setItem('user', JSON.stringify(user));
// Retrieve object from localStorage
const storedUser = JSON.parse(localStorage.getItem('user'));
console.log(storedUser.preferences.theme); // dark
2. AJAX/Fetch API:
// Sending data to server
const data = {name: "Alice", course: "CST463"};
fetch('/api/students', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data) // Convert to JSON string
})
.then(response => response.json()) // Parse JSON response
.then(result => {
console.log('Success:', result);
});
3. Deep Cloning Objects:
const original = {name: "John", courses: ["Math", "Physics"]};
// Quick deep clone (limitations: doesn't copy functions, Dates become strings)
const clone = JSON.parse(JSON.stringify(original));
clone.courses.push("Chemistry");
console.log(original.courses.length); // 2 (unchanged)
console.log(clone.courses.length); // 3 (modified)
4. API Response Handling:
// Simulating API response
const apiResponse = '{"status":"success","data":{"students":[{"id":1,"name":"John"},{"id":2,"name":"Mary"}]}}';
const response = JSON.parse(apiResponse);
if (response.status === "success") {
response.data.students.forEach(student => {
console.log(`ID: ${student.id}, Name: ${student.name}`);
});
}
Comparison:
| Aspect | JSON.stringify() | JSON.parse() |
|---|---|---|
| Purpose | JavaScript β JSON string | JSON string β JavaScript |
| Input | JS object/array/value | JSON string |
| Output | JSON string | JS object/array/value |
| Use Case | Send data to server | Receive data from server |
| Error | Rarely throws errors | Throws SyntaxError on invalid JSON |
Complete Example:
// Original JavaScript object
const studentRecord = {
id: 101,
name: "Rajesh Kumar",
courses: ["CST463", "CST401", "CST301"],
grades: {
CST463: "A",
CST401: "A+",
CST301: "B"
},
enrolled: true,
graduationYear: null
};
console.log("Original Object:", studentRecord);
console.log("Type:", typeof studentRecord); // object
// Convert to JSON string
const jsonString = JSON.stringify(studentRecord, null, 2);
console.log("\nJSON String:\n", jsonString);
console.log("Type:", typeof jsonString); // string
// Store in localStorage (requires string)
localStorage.setItem('student', jsonString);
// Retrieve and parse
const retrieved = localStorage.getItem('student');
const parsedStudent = JSON.parse(retrieved);
console.log("\nParsed Object:", parsedStudent);
console.log("Type:", typeof parsedStudent); // object
console.log("Name:", parsedStudent.name); // Rajesh Kumar
console.log("Grade in CST463:", parsedStudent.grades.CST463); // A
Key Points:
- JSON.stringify() converts JS to JSON string - used before sending to server
- JSON.parse() converts JSON string to JS - used after receiving from server
- Always use try-catch with JSON.parse() for error handling
- Functions, undefined, and Symbols are omitted during stringify
- Dates become strings during stringify
- Use reviver parameter to transform values during parsing
- Essential for localStorage, API communication, and data exchange
Summary:
JSON.stringify() converts JavaScript objects to JSON strings for data transmission, while JSON.parse() converts JSON strings back to JavaScript objects. These methods are fundamental for client-server communication, local storage, and data serialization in modern web applications.
Mark Distribution:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUESTION 20(b) - MARK DISTRIBUTION (Total: 6 marks) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Component β Marks β
ββββββββββββββββββββββββββββββββββββββββββββββββββΌβββββββββββββ€
β 1. JSON.parse() Functionality β 3 marks β
β - Purpose and syntax β β
β - Converting JSON string to JS object β β
β - Parameters and examples β β
β β β
β 2. JSON.stringify() Functionality β 3 marks β
β - Purpose and syntax β β
β - Converting JS object to JSON string β β
β - Parameters and examples β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
END OF ANSWER KEY