0% found this document useful (0 votes)
2 views

DOM Manipulation and Event Handling

The document outlines the creation of a webpage with DOM manipulation and event handling, form validation, user login/logout with sessions, and server-side validation in PHP. It includes HTML and JavaScript code for a name reveal feature, form validation for various fields, and a simple login system. Each section provides detailed instructions and code snippets for implementation.

Uploaded by

dragonlusion
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

DOM Manipulation and Event Handling

The document outlines the creation of a webpage with DOM manipulation and event handling, form validation, user login/logout with sessions, and server-side validation in PHP. It includes HTML and JavaScript code for a name reveal feature, form validation for various fields, and a simple login system. Each section provides detailed instructions and code snippets for implementation.

Uploaded by

dragonlusion
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

1. DOM Manipulation and Event Handling.

Task:
Create a webpage that initially displays a paragraph with the text "What's my name?" and
a button labeled "Reveal Name." When the button is clicked, the following actions should
occur:
• The paragraph text should change to "My name is [Your Name]!" (replace [Your
Name] with your actual name).
• The paragraph should be styled with a background color of gray.
• The button text should change to "Hide Name."
• If the button is clicked again, the paragraph text should revert to "What's my name?"
and the original styles should be removed, while the button text should change back
to "Reveal Name."

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Manipulation and Event Handling</title>
<style>
.gray-background {
background-color: gray;
color: white;
}
</style>
</head>
<body>
<p id="name-paragraph">What's my name?</p>
<button id="toggle-button">Reveal Name</button>

<script>
const paragraph = document.getElementById('name-paragraph');
const button = document.getElementById('toggle-button');

button.addEventListener('click', () => {
if (button.textContent === 'Reveal Name') {
paragraph.textContent = 'My name is [Your Name]!';
paragraph.classList.add('gray-background');
button.textContent = 'Hide Name';
} else {
paragraph.textContent = "What's my name?";
paragraph.classList.remove('gray-background');
button.textContent = 'Reveal Name';
}
});
</script>
</body>
</html>

2. Form Validation / Client-side scripting

Write a JavaScript program that performs form validation with the following requirements:
A. Form Fields:
o Full Name: Required field. Must not be empty.
o Email: Required field. Must be a valid email address.
o Username: Required field. Must not be empty.
o Password: Required field. Must be at least 8 characters long and include at
least one letter and one number.
o Confirm Password: Must match the password field.

o Date of Birth: Required field. The age should be between 18 and 99 years
old.
o Phone Number: Required field. Must be a valid Nepali phone number.
o Gender: Required field. Must select either "Male" or "Female".

<!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>
</head>
<body>
<form id="myForm" onsubmit="return validateForm()">
<label for="fullName">Full Name:</label>
<input type="text" id="fullName" name="fullName"><br>

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

<label for="username">Username:</label>
<input type="text" id="username" name="username"><br>

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

<label for="confirmPassword">Confirm Password:</label>


<input type="password" id="confirmPassword" name="confirmPassword"><br>

<label for="dob">Date of Birth:</label>


<input type="date" id="dob" name="dob"><br>

<label for="phone">Phone Number:</label>


<input type="text" id="phone" name="phone"><br>

<label for="gender">Gender:</label>
<select id="gender" name="gender">
<option value="">Select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select><br>

<input type="submit" value="Submit">


</form>

<script>
function validateForm() {
// Full Name
const fullName = document.getElementById('fullName').value;
if (fullName === '') {
alert('Full Name is required.');
return false;
}

// Email
const email = document.getElementById('email').value;
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
alert('Please enter a valid email address.');
return false;
}

// Username
const username = document.getElementById('username').value;
if (username === '') {
alert('Username is required.');
return false;
}

// Password
const password = document.getElementById('password').value;
const passwordPattern = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (!passwordPattern.test(password)) {
alert('Password must be at least 8 characters long and include at least one letter and one number.');
return false;
}

// Confirm Password
const confirmPassword = document.getElementById('confirmPassword').value;
if (password !== confirmPassword) {
alert('Passwords do not match.');
return false;
}

// Date of Birth
const dob = new Date(document.getElementById('dob').value);
const age = new Date().getFullYear() - dob.getFullYear();
if (age < 18 || age > 99) {
alert('Age must be between 18 and 99 years.');
return false;
}

// Phone Number
const phone = document.getElementById('phone').value;
const phonePattern = /^[9][6-9]\d{8}$/;
if (!phonePattern.test(phone)) {
alert('Please enter a valid Nepali phone number.');
return false;
}

// Gender
const gender = document.getElementById('gender').value;
if (gender === '') {
alert('Gender is required.');
return false;
}

alert('Form submitted successfully!');


return true;
}
</script>
</body>
</html>

Instructions:
o Create an HTML form with the above fields.
o Implement JavaScript to validate each field according to the requirements.
o Show error messages below each field in red if validation fails.
o Display a confirmation message on the same page if all validations pass.

<!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>
<style>
.error {
color: red;
}
.confirmation {
color: green;
}
</style>
</head>
<body>
<form id="myForm" onsubmit="return validateForm()">
<label for="fullName">Full Name:</label>
<input type="text" id="fullName" name="fullName"><br>
<span id="fullNameError" class="error"></span><br>

<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>
<span id="emailError" class="error"></span><br>

<label for="username">Username:</label>
<input type="text" id="username" name="username"><br>
<span id="usernameError" class="error"></span><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password"><br>
<span id="passwordError" class="error"></span><br>

<label for="confirmPassword">Confirm Password:</label>


<input type="password" id="confirmPassword" name="confirmPassword"><br>
<span id="confirmPasswordError" class="error"></span><br>

<label for="dob">Date of Birth:</label>


<input type="date" id="dob" name="dob"><br>
<span id="dobError" class="error"></span><br>

<label for="phone">Phone Number:</label>


<input type="text" id="phone" name="phone"><br>
<span id="phoneError" class="error"></span><br>

<label for="gender">Gender:</label>
<select id="gender" name="gender">
<option value="">Select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select><br>
<span id="genderError" class="error"></span><br>

<input type="submit" value="Submit">


</form>

<p id="confirmationMessage" class="confirmation"></p>

<script>
function validateForm() {
// Clear previous error messages
document.querySelectorAll('.error').forEach(element => element.textContent = '');
document.getElementById('confirmationMessage').textContent = '';

// Validate fields
let isValid = true;

// Full Name
const fullName = document.getElementById('fullName').value;
if (fullName === '') {
document.getElementById('fullNameError').textContent = 'Full Name is required.';
isValid = false;
}

// Email
const email = document.getElementById('email').value;
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
document.getElementById('emailError').textContent = 'Please enter a valid email address.';
isValid = false;
}

// Username
const username = document.getElementById('username').value;
if (username === '') {
document.getElementById('usernameError').textContent = 'Username is required.';
isValid = false;
}

// Password
const password = document.getElementById('password').value;
const passwordPattern = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (!passwordPattern.test(password)) {
document.getElementById('passwordError').textContent = 'Password must be at least 8 characters long and include at
least one letter and one number.';
isValid = false;
}

// Confirm Password
const confirmPassword = document.getElementById('confirmPassword').value;
if (password !== confirmPassword) {
document.getElementById('confirmPasswordError').textContent = 'Passwords do not match.';
isValid = false;
}

// Date of Birth
const dob = new Date(document.getElementById('dob').value);
const age = new Date().getFullYear() - dob.getFullYear();
if (age < 18 || age > 99) {
document.getElementById('dobError').textContent = 'Age must be between 18 and 99 years.';
isValid = false;
}

// Phone Number
const phone = document.getElementById('phone').value;
const phonePattern = /^[9][6-9]\d{8}$/;
if (!phonePattern.test(phone)) {
document.getElementById('phoneError').textContent = 'Please enter a valid Nepali phone number.';
isValid = false;
}

// Gender
const gender = document.getElementById('gender').value;
if (gender === '') {
document.getElementById('genderError').textContent = 'Gender is required.';
isValid = false;
}

if (isValid) {
document.getElementById('confirmationMessage').textContent = 'Form submitted successfully!';
}

return isValid;
}
</script>
</body>
</html>
3. User Login and Logout with Sessions

Step A: Create a login form (examples.php)

php
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Form</title></head><body>
<form action="login.php" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br>

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

<input type="submit" value="Login">


</form>
<?php
if (isset($_GET['error'])) {
echo '<p style="color:red;">'.htmlspecialchars($_GET['error']).'</p>';
}
?></body></html>

Step B: Implement a login system in PHP (login.php)

php
<?
phpsession_start();
$hardcoded_username = "admin";$hardcoded_password = "password123";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];

if ($username === $hardcoded_username && $password === $hardcoded_password) {


$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
header("Location: dashboard.php");
exit();
} else {
$error_message = "Invalid username or password.";
header("Location: examples.php?error=" . urlencode($error_message));
exit();
}}?>

Step C: Implement a welcome page (dashboard.php)

php
<?
phpsession_start();
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
header("Location: examples.php");
exit();}?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard</title></head><body>
<h1>Welcome,
<?php echo htmlspecialchars($_SESSION['username']); ?>!</h1>
<a href="logout.php">Logout</a>
</body>
</html>

Step D: Implement a logout system (logout.php)

php
<?
phpsession_start();session_unset();
session_destroy();?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Logged Out</title>
</head>
<body>
<p>You have been logged out.</p>
<a href="examples.php">Login Again</a>
</body>
</html>

4. Form Validation in PHP


Instructions:
1. Form Design:
o Create a web form in examples.php with the following fields:
o Full Name: Required field. Must not be empty.
o Email: Required field. Must be a valid email address.
o Username: Required field. Must not be empty.
o Password: Required field. Must be at least 8 characters long and include at
least one letter and one number.
o Confirm Password: Must match the password field.

o Date of Birth: Required field. The age should be between 18 and 99 years
old.
o Phone Number: Required field. Must be a valid Nepali phone number.
o Gender: Required field. Must select either "Male" or "Female".
o Ensure the form uses the POST method to submit data to phptest.php.

Server-Side Validation:
• In phptest.php, write PHP code to:
o Validate each input field.
o Display appropriate error messages if any validation fails.
o If all validations pass, display the submitted data back to the user.

<!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>
</head>
<body>
<form action="phptest.php" method="POST">
<label for="fullName">Full Name:</label>
<input type="text" id="fullName" name="fullName" required><br>

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

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

<label for="confirmPassword">Confirm Password:</label>


<input type="password" id="confirmPassword" name="confirmPassword" required><br>

<label for="dob">Date of Birth:</label>


<input type="date" id="dob" name="dob" required><br>

<label for="phone">Phone Number:</label>


<input type="text" id="phone" name="phone" required><br>

<label for="gender">Gender:</label>
<select id="gender" name="gender" required>
<option value="">Select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select><br>

<input type="submit" value="Submit">


</form>
</body>
</html>

write the PHP code for phptest.php to validate each input field and display appropriate error messages or the
submitted data:

<?php
function validate_date_of_birth($dob) {
$age = (new DateTime())->diff(new DateTime($dob))->y;
return ($age >= 18 && $age <= 99);
}

function validate_phone_number($phone) {
return preg_match('/^[9][6-9]\d{8}$/', $phone);
}

$errors = [];
$data = [];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Full Name
if (empty($_POST["fullName"])) {
$errors["fullName"] = "Full Name is required.";
} else {
$data["fullName"] = $_POST["fullName"];
}

// Email
if (empty($_POST["email"]) || !filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
$errors["email"] = "Valid Email is required.";
} else {
$data["email"] = $_POST["email"];
}

// Username
if (empty($_POST["username"])) {
$errors["username"] = "Username is required.";
} else {
$data["username"] = $_POST["username"];
}

// Password
if (empty($_POST["password"]) || !preg_match('/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/',
$_POST["password"])) {
$errors["password"] = "Password must be at least 8 characters long and include at least one letter and
one number.";
}

// Confirm Password
if (empty($_POST["confirmPassword"]) || $_POST["confirmPassword"] !== $_POST["password"]) {
$errors["confirmPassword"] = "Passwords do not match.";
}

// Date of Birth
if (empty($_POST["dob"]) || !validate_date_of_birth($_POST["dob"])) {
$errors["dob"] = "Valid Date of Birth is required (Age 18-99).";
} else {
$data["dob"] = $_POST["dob"];
}

// Phone Number
if (empty($_POST["phone"]) || !validate_phone_number($_POST["phone"])) {
$errors["phone"] = "Valid Nepali Phone Number is required.";
} else {
$data["phone"] = $_POST["phone"];
}

// Gender
if (empty($_POST["gender"])) {
$errors["gender"] = "Gender is required.";
} else {
$data["gender"] = $_POST["gender"];
}
if (empty($errors)) {
echo "<h2>Submitted Data:</h2>";
foreach ($data as $key => $value) {
echo"<p>".htmlspecialchars(ucfirst($key)).": ".htmlspecialchars($value)."</p>";
}
} else {
echo "<h2>Errors:</h2>";
foreach ($errors as $error) {
echo "<p style='color:red;'>".htmlspecialchars($error)."</p>";
}
echo "<p><a href='examples.php'>Go back to the form</a></p>";
}
}
?>

5. Implement OOP concepts such as classes, objects, constructors, destructors,


inheritance, and method overriding using PHP.
Instructions:
A. Create a class named Person:
o Define the following properties: name, age, and gender.
o Create a constructor to initialize these properties when an object is created.
o Write a method called getDetails() to display the person's details.
o Add a destructor to the class that outputs a message when the object is
destroyed.

B. Create a class named Employee that extends the Person class:


o Add a property salary specific to the Employee class.
o Override the getDetails() method to include the salary in the details output.
o Use the destructor to indicate when the Employee object is destroyed.
C. Write a PHP script to:
o Create an instance of the Person class and display their details.
o Create an instance of the Employee class and display their details using the
overridden method.
o Demonstrate the concept of inheritance, method overriding, and destructors.
o When each object is destroyed, the destructor should output a message.

Step A: Create a class named Person

php
<?phpclass Person {
public $name;
public $age;
public $gender;

// Constructor to initialize properties


public function __construct($name, $age, $gender) {
$this->name = $name;
$this->age = $age;
$this->gender = $gender;
}

// Method to display person's details


public function getDetails() {
return "Name: {$this->name}, Age: {$this->age}, Gender: {$this->gender}";
}

// Destructor
public function __destruct() {
echo "Person object for {$this->name} is being destroyed.\n";
}}?>

Step B: Create a class named Employee that extends Person

php
<?phpclass Employee extends Person {
public $salary;

// Constructor to initialize properties including salary


public function __construct($name, $age, $gender, $salary) {
parent::__construct($name, $age, $gender); // Call the parent constructor
$this->salary = $salary;
}

// Override getDetails method to include salary


public function getDetails() {
return parent::getDetails() . ", Salary: {$this->salary}";
}
// Destructor
public function __destruct() {
echo "Employee object for {$this->name} is being destroyed.\n";
}}?>

Step C: Write a PHP script to demonstrate the concepts

<?php
// Include the class definitions
include 'Person.php';
include 'Employee.php';

// Create an instance of the Person class


$person = new Person("John Doe", 30, "Male");
echo $person->getDetails() . "\n";

// Create an instance of the Employee class


$employee = new Employee("Jane Smith", 25, "Female", 50000);
echo $employee->getDetails() . "\n";

// The destructors will automatically be called at the end of the script


?>

concise demonstration of inheritance, method overriding, and destructors in PHP

Person.php

php
<?phpclass Person {
public $name;
public $age;
public $gender;

// Constructor to initialize properties


public function __construct($name, $age, $gender) {
$this->name = $name;
$this->age = $age;
$this->gender = $gender;
echo "Person object for {$this->name} is created.\n";
}

// Method to display person's details


public function getDetails() {
return "Name: {$this->name}, Age: {$this->age}, Gender: {$this->gender}";
}

// Destructor
public function __destruct() {
echo "Person object for {$this->name} is being destroyed.\n";
}}?>

Employee.php

php
<?phpinclude 'Person.php';
class Employee extends Person {
public $salary;

// Constructor to initialize properties including salary


public function __construct($name, $age, $gender, $salary) {
parent::__construct($name, $age, $gender); // Call the parent constructor
$this->salary = $salary;
echo "Employee object for {$this->name} with salary {$this->salary} is created.\n";
}

// Override getDetails method to include salary


public function getDetails() {
return parent::getDetails() . ", Salary: {$this->salary}";
}

// Destructor
public function __destruct() {
echo "Employee object for {$this->name} is being destroyed.\n";
}}?>

Demonstration Script (demo.php)

php
<?phpinclude 'Employee.php';
// Create an instance of the Person class$person = new Person("John Doe", 30, "Male");echo $person->getDetails() . "\n";
// Create an instance of the Employee class$employee = new Employee("Jane Smith", 25, "Female", 50000);echo $employee-
>getDetails() . "\n";
// The destructors will automatically be called at the end of the script?>

Expected Output:

6. Multiple Inheritance Using Traits in PHP


Instructions:
A. Create a Trait for Logging
o Create a trait called Logger that contains a method log($message) to display
a logging message.
B. Create a Trait for Notification
o Create another trait called Notifier that contains a method
sendNotification($message) to simulate sending a notification.
C. Create a Base Class
o Create a base class called User, with a method getUserDetails($name) that
outputs the user’s name.
D. Create a Class for Application
o Create a class called App that extends the User class and uses both the
Logger and Notifier traits.
E. Demonstrate Multiple Inheritance
o In the App class, use the methods from the traits (log and sendNotification),
and from the base class (getUserDetails).
F. Destructor
o Add a destructor in the App class that outputs a message when the object is
Destroyed
Step A: Create a Trait for Logging

php
<?phptrait Logger {
public function log($message) {
echo "Log message: $message\n";
}}?>

Step B: Create a Trait for Notification

php
<?phptrait Notifier {
public function sendNotification($message) {
echo "Notification: $message\n";
}}?>

Step C: Create a Base Class

php
<?phpclass User {
public function getUserDetails($name) {
echo "User's Name: $name\n";
}}?>

Step D: Create a Class for Application

php
<?phpinclude 'Logger.php';include 'Notifier.php';include 'User.php';
class App extends User {
use Logger, Notifier;

// Destructor
public function __destruct() {
echo "App object is being destroyed.\n";
}}?>

Step E: Demonstrate Multiple Inheritance

php
<?phpinclude 'App.php';
// Create an instance of the App class$app = new App();$app->getUserDetails("John Doe");$app->log("This is a log message.");
$app->sendNotification("You have a new message!");
// The destructor will automatically be called at the end of the script
?>

7. Polymorphism in PHP
Instructions:
A. Create a Base Class: Animal
o Create a class Animal with a method sound() that outputs a generic message
like "Animal makes a sound."

B. Create Derived Classes: Dog and Cat


o Create two classes Dog and Cat, both extending the Animal class.
o In each class, override the sound() method to display a specific message:
▪ Dog: "Dog barks"
▪ Cat: "Cat meows"

C. Create a Function to Accept Animal Object


o Create a function makeSound(Animal $animal) that calls the sound()
method of the passed object. This will demonstrate polymorphism.
D.Interface Example
o Create an interface AnimalBehavior with a method move().
o Implement the move() method in both Dog and Cat classes to demonstrate
how both classes implement the same interface but behave differently.
E. Destructor
o Add a destructor in both Dog and Cat classes to output a message when the
object is destroyed.

A: Create a Base Class Animal

php
<?phpclass Animal {
public function sound() {
echo "Animal makes a sound.\n";
}}?>

B: Create Derived Classes Dog and Cat


<?php
include 'Animal.php';

class Dog extends Animal {


// Override the sound method
public function sound() {
echo "Dog barks.\n";
}

// Destructor
public function __destruct() {
echo "Dog object is being destroyed.\n";
}
}

class Cat extends Animal {


// Override the sound method
public function sound() {
echo "Cat meows.\n";
}

// Destructor
public function __destruct() {
echo "Cat object is being destroyed.\n";
}
}
?>
C: Create a Function to Accept Animal Object
<?php
function makeSound(Animal $animal) {
$animal->sound();
}
?>
D: Interface Example
<?php
interface AnimalBehavior {
public function move();
}

class Dog extends Animal implements AnimalBehavior {


// Override the sound method
public function sound() {
echo "Dog barks.\n";
}

// Implement the move method


public function move() {
echo "Dog runs.\n";
}

// Destructor
public function __destruct() {
echo "Dog object is being destroyed.\n";
}
}

class Cat extends Animal implements AnimalBehavior {


// Override the sound method
public function sound() {
echo "Cat meows.\n";
}

// Implement the move method


public function move() {
echo "Cat jumps.\n";
}

// Destructor
public function __destruct() {
echo "Cat object is being destroyed.\n";
}
}
?>
Demonstration Script (demo.php)
<?php
include 'Dog.php';
include 'Cat.php';
include 'makeSound.php';

// Create an instance of the Dog class


$dog = new Dog();
$dog->sound();
$dog->move();
makeSound($dog);

// Create an instance of the Cat class


$cat = new Cat();
$cat->sound();
$cat->move();
makeSound($cat);

// The destructors will automatically be called at the end of the script


?>

Expected Output:

8. PHP and MySQL - Establishing Connection, Creating a Table, and Inserting Values
Task:
A. Establish Connection to MySQL Database:
Write a PHP script to connect to a MySQL database using the mysqli extension.
The connection should be established with a database student_db.
B. Create a Table:
After establishing the connection, write a query to create a table named students
with the following columns:
o id
o name
o age
C. Insert Values

D. Display a Success Message:


Once the table is created and values are inserted, display a message like "Table
created and values inserted successfully!" if no errors occur.

A: Establish Connection to MySQL Database


<?php
// Database credentials
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "student_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully\n";
?>

B: Create a Table
<?php
// SQL to create table
$sql = "CREATE TABLE IF NOT EXISTS students (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
age INT(3) NOT NULL
)";

if ($conn->query($sql) === TRUE) {


echo "Table students created successfully\n";
} else {
echo "Error creating table: " . $conn->error;
}
?>
C: Insert Values
<?php
// SQL to insert values
$sql = "INSERT INTO students (name, age) VALUES
('Alice', 20),
('Bob', 22),
('Charlie', 19)";

if ($conn->query($sql) === TRUE) {


echo "Values inserted successfully\n";
} else {
echo "Error inserting values: " . $conn->error;
}
?>
D: Display Success Message
<?php
if ($conn->query($sql) === TRUE) {
echo "Table created and values inserted successfully!";
} else {
echo "Error: " . $conn->error;
}

// Close connection
$conn->close();
?>
Complete Script::
<?php
// Database credentials
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "student_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully\n";

// SQL to create table


$sql = "CREATE TABLE IF NOT EXISTS students (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
age INT(3) NOT NULL
)";

if ($conn->query($sql) === TRUE) {


echo "Table students created successfully\n";
} else {
echo "Error creating table: " . $conn->error;
}

// SQL to insert values


$sql = "INSERT INTO students (name, age) VALUES
('Alice', 20),
('Bob', 22),
('Charlie', 19)";

if ($conn->query($sql) === TRUE) {


echo "Values inserted successfully\n";
} else {
echo "Error inserting values: " . $conn->error;
}

echo "Table created and values inserted successfully!";

// Close connection
$conn->close();
?>

9. MySQL Queries - ORDER BY, GROUP BY, and Joins


Objective: Practice using ORDER BY, GROUP BY, and JOIN clauses in MySQL with
PHP to manage and query data effectively.
Task:
A. Create Two Tables:
Write a PHP script that establishes a connection to the student_db database (from
the previous lab) and creates two tables:
o students (if not already created) with columns:
▪ id (Primary Key, auto-increment)
▪ name (VARCHAR, 50)
▪ age (INT)
o courses with columns:
▪ course_id (Primary Key, auto-increment)
▪ student_id (Foreign Key referencing students.id)
▪ course_name (VARCHAR, 100)

B. Insert Values:
After creating the tables, insert the following records:
o In students table:
▪ Name: John Doe, Age: 25
▪ Name: Jane Smith, Age: 30
▪ Name: Alice Johnson, Age: 22
o In courses table:
▪ Course Name: PHP, Student ID: 1
▪ Course Name: MySQL, Student ID: 1
▪ Course Name: JavaScript, Student ID: 2
▪ Course Name: PHP, Student ID: 3

C. ORDER BY Query:
Write a query to fetch the details of all students from the students table, ordered
by their age in descending order.

D. GROUP BY Query:
Write a query to display the number of students enrolled in each course. Use the
GROUP BY clause to group by course_name in the courses table.
E. JOIN Query:
Write a query that performs an INNER JOIN between the students and courses
tables to display each student's name along with the courses they are enrolled in.
F. Display Results:
Display the results of each query in a structured format using echo in PHP. If no
results are found, display an appropriate message.

A: Create Two Tables


<?php
// Database credentials
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "student_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// SQL to create students table


$sql = "CREATE TABLE IF NOT EXISTS students (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT(3) NOT NULL
)";
if ($conn->query($sql) === TRUE) {
echo "Table students created successfully\n";
} else {
echo "Error creating table: " . $conn->error . "\n";
}

// SQL to create courses table


$sql = "CREATE TABLE IF NOT EXISTS courses (
course_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
student_id INT(6) UNSIGNED,
course_name VARCHAR(100) NOT NULL,
FOREIGN KEY (student_id) REFERENCES students(id)
)";
if ($conn->query($sql) === TRUE) {
echo "Table courses created successfully\n";
} else {
echo "Error creating table: " . $conn->error . "\n";
}
?>

B: Insert Values
<?php
// Insert values into students table
$sql = "INSERT INTO students (name, age) VALUES
('John Doe', 25),
('Jane Smith', 30),
('Alice Johnson', 22)";
if ($conn->query($sql) === TRUE) {
echo "Values inserted into students table successfully\n";
} else {
echo "Error inserting values: " . $conn->error . "\n";
}

// Insert values into courses table


$sql = "INSERT INTO courses (course_name, student_id) VALUES
('PHP', 1),
('MySQL', 1),
('JavaScript', 2),
('PHP', 3)";
if ($conn->query($sql) === TRUE) {
echo "Values inserted into courses table successfully\n";
} else {
echo "Error inserting values: " . $conn->error . "\n";
}
?>

C: ORDER BY Query
<?php
// Query to fetch student details ordered by age in descending order
$sql = "SELECT * FROM students ORDER BY age DESC";
$result = $conn->query($sql);

echo "Students ordered by age (desc):\n";


if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Age: " . $row["age"]. "\n";
}
} else {
echo "No students found\n";
}
?>
D: GROUP BY Query
<?php
// Query to count the number of students enrolled in each course
$sql = "SELECT course_name, COUNT(*) as student_count FROM courses GROUP BY course_name";
$result = $conn->query($sql);

echo "Number of students enrolled in each course:\n";


if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Course: " . $row["course_name"]. " - Students: " . $row["student_count"]. "\n";
}
} else {
echo "No courses found\n";
}
?>

E: JOIN Query
<?php
// Query to perform an INNER JOIN between students and courses
$sql = "SELECT students.name, courses.course_name FROM students INNER JOIN courses ON students.id
= courses.student_id";
$result = $conn->query($sql);

echo "Students and their courses:\n";


if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"]. " - Course: " . $row["course_name"]. "\n";
}
} else {
echo "No students enrolled in any courses\n";
}
?>

Complete Script
<?php
// Database credentials
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "student_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Create tables
$sql = "CREATE TABLE IF NOT EXISTS students (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT(3) NOT NULL
)";
$conn->query($sql);

$sql = "CREATE TABLE IF NOT EXISTS courses (


course_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
student_id INT(6) UNSIGNED,
course_name VARCHAR(100) NOT NULL,
FOREIGN KEY (student_id) REFERENCES students(id)
)";
$conn->query($sql);
// Insert values
$sql = "INSERT INTO students (name, age) VALUES
('John Doe', 25),
('Jane Smith', 30),
('Alice Johnson', 22)";
$conn->query($sql);

$sql = "INSERT INTO courses (course_name, student_id) VALUES


('PHP', 1),
('MySQL', 1),
('JavaScript', 2),
('PHP', 3)";
$conn->query($sql);

// ORDER BY query
$sql = "SELECT * FROM students ORDER BY age DESC";
$result = $conn->query($sql);
echo "Students ordered by age (desc):\n";
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Age: " . $row["age"]. "\n";
}
} else {
echo "No students found\n";
}

// GROUP BY query
$sql = "SELECT course_name, COUNT(*) as student_count FROM courses GROUP BY course_name";
$result = $conn->query($sql);
echo "Number of students enrolled in each course:\n";
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Course: " . $row["course_name"]. " - Students: " . $row["student_count"]. "\n";
}
} else {
echo "No courses found\n";
}

// JOIN query
$sql = "SELECT students.name, courses.course_name FROM students INNER JOIN courses ON students.id
= courses.student_id";
$result = $conn->query($sql);
echo "Students and their courses:\n";
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"]. " - Course: " . $row["course_name"]. "\n";
}
} else {
echo "No students enrolled in any courses\n";
}

// Close connection
$conn->close();
?>
10. jQuery
Task:
You are provided with a basic HTML file containing a paragraph, a list of items, a div, and
an image. Using jQuery, perform the following tasks:
A. Change the Paragraph Background Color:
Add a button that changes the background color of the paragraph to light blue
when clicked.
B. Hide the List of Items:
Implement a button that hides the list using a sliding animation.
C. Animate the Div Width:
Create a button that increases the width of the div from 300px to 500px over a
period of 1 second.
D. Highlight Even List Items:
Using jQuery, set the color of even-numbered list items to red.
E. Control Image Visibility:
Add three buttons to:
o Hide the image.
o Show the hidden image.
o Toggle between hiding and showing the image on each button press.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Tasks</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#myDiv {
width: 300px;
height: 100px;
background-color: lightgray;
}
</style>
</head>
<body>
<p id="myParagraph">This is a paragraph.</p>
<button id="changeColorBtn">Change Paragraph Color</button>

<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
<button id="hideListBtn">Hide List</button>

<div id="myDiv"></div>
<button id="animateDivBtn">Animate Div Width</button>

<img id="myImage" src="example.jpg" alt="Example Image" width="200">


<button id="hideImageBtn">Hide Image</button>
<button id="showImageBtn">Show Image</button>
<button id="toggleImageBtn">Toggle Image</button>

<script>
$(document).ready(function() {
// Task A: Change Paragraph Background Color
$('#changeColorBtn').click(function() {
$('#myParagraph').css('background-color', 'lightblue');
});

// Task B: Hide the List of Items


$('#hideListBtn').click(function() {
$('#myList').slideUp();
});

// Task C: Animate the Div Width


$('#animateDivBtn').click(function() {
$('#myDiv').animate({ width: '500px' }, 1000);
});

// Task D: Highlight Even List Items


$('#myList li:even').css('color', 'red');

// Task E: Control Image Visibility


$('#hideImageBtn').click(function() {
$('#myImage').hide();
});

$('#showImageBtn').click(function() {
$('#myImage').show();
});

$('#toggleImageBtn').click(function() {
$('#myImage').toggle();
});
});
</script>
</body>
</html>

11. AJAX

You are required to create a web page that accepts a user's name and age, and then allows
them to submit the data to the server using either the GET or POST method. On the
backend, implement a PHP script (fetch_data.php) that handles both GET and POST
requests, inserts the data into a MySQL database, and returns a confirmation message.
Tasks:
A. Create a MySQL database called user_db and a table named users. (columns:
id(pk), name, age)
B. Design a simple HTML form with the following fields:
• Name: Text field
• Age: Text field
• Two buttons:
o "Submit via GET": Triggers a GET request
o "Submit via POST": Triggers a POST request

C. Write JavaScript functions to send the form data to the server using AJAX. When
a user clicks on one of the buttons, the corresponding function should:
• Retrieve values from the input fields.
• Make an asynchronous request to the server using the chosen method (GET or
POST).
D. Implement a fetch_data.php script that:
• Establishes a connection to the MySQL database.
• Detects whether the request is GET or POST.
• Inserts the data into the users table and sends an appropriate response back.

E. Display the server’s response (confirmation message) in a <div> below the form
without reloading the page.

A: Create a MySQL Database and Table


CREATE DATABASE user_db;

USE user_db;

CREATE TABLE users (


id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT(3) NOT NULL
);
B: Design the HTML Form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX Form</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form id="userForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br>

<label for="age">Age:</label>
<input type="text" id="age" name="age" required><br>

<button type="button" onclick="submitForm('GET')">Submit via GET</button>


<button type="button" onclick="submitForm('POST')">Submit via POST</button>
</form>

<div id="responseMessage"></div>

<script>
function submitForm(method) {
let name = $('#name').val();
let age = $('#age').val();
let url = 'fetch_data.php';

$.ajax({
url: url,
type: method,
data: {
name: name,
age: age
},
success: function(response) {
$('#responseMessage').html(response);
},
error: function() {
$('#responseMessage').html('An error occurred');
}
});
}
</script>
</body>
</html>
D: Implement fetch_data.php Script
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "user_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Get data from request


$name = "";
$age = "";
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$name = $_GET['name'];
$age = $_GET['age'];
} elseif ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$age = $_POST['age'];
}

// Insert data into table


$sql = "INSERT INTO users (name, age) VALUES ('$name', '$age')";
if ($conn->query($sql) === TRUE) {
echo "Data inserted successfully!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

// Close connection
$conn->close();
?>
E: Display the Server’s Response

You might also like