0% found this document useful (0 votes)
147 views44 pages

Sybba (Ca) Lab Book Solution

The document contains multiple lab assignments focusing on PHP programming. It includes tasks such as creating classes for employee management, distance conversion, and a calculator, along with their respective implementations. Each assignment provides a structured approach to solving problems using object-oriented programming concepts.

Uploaded by

shraddhavinod1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
147 views44 pages

Sybba (Ca) Lab Book Solution

The document contains multiple lab assignments focusing on PHP programming. It includes tasks such as creating classes for employee management, distance conversion, and a calculator, along with their respective implementations. Each assignment provides a structured approach to solving problems using object-oriented programming concepts.

Uploaded by

shraddhavinod1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Lab Assignment 1

Set A:
1) Write class declarations and member function definitions for an
employee(code, name, designation). Derive emp_account(account_no,
joining_date) from employee and emp_sal(basic_pay, earnings, deduction) from
emp_account. Write a menu drivenprogram
a) To build a mastertable
b) To sort allentries
c) To search anentry
d) Display salary
Solutiojn-:
<?php
class Employee {
public $code;
public $name;
public $designation;
function __construct($code, $name, $designation) {
$this->code = $code;
$this->name = $name;
$this->designation = $designation;
}
}
class EmpAccount extends Employee {
public $account_no;
public $joining_date;
function __construct($code, $name, $designation, $account_no,
$joining_date) {
parent::__construct($code, $name, $designation);
$this->account_no = $account_no;
$this->joining_date = $joining_date;
}
}
class EmpSal extends EmpAccount {
public $basic_pay;
public $earnings;
public $deduction;
function __construct($code, $name, $designation, $account_no,
$joining_date, $basic_pay, $earnings, $deduction) {
parent::__construct($code, $name, $designation, $account_no,
$joining_date);
$this->basic_pay = $basic_pay;
$this->earnings = $earnings;
$this->deduction = $deduction;
}
function getSalary() {
return $this->basic_pay + $this->earnings - $this->deduction;
}
}
$employeeRecords = [];
function buildMasterTable() {
global $employeeRecords;
$emp = new EmpSal("E001", "John Doe", "Software Developer",
"ACC001", "2020-01-01", 50000, 10000, 5000);
array_push($employeeRecords, $emp);
$emp = new EmpSal("E002", "Jane Smith", "HR Manager", "ACC002",
"2018-03-15", 60000, 15000, 4000);
array_push($employeeRecords, $emp);
echo "Master table has been created with sample entries.\n";
}
function sortEntries() {
global $employeeRecords;
usort($employeeRecords, function($a, $b) {
return strcmp($a->code, $b->code); // Sorting by employee code
});
echo "Employee records sorted by code.\n";
}
function searchEntry($code) {
global $employeeRecords;
foreach ($employeeRecords as $emp) {
if ($emp->code == $code) {
echo "Employee found: \n";
echo "Code: " . $emp->code . "\n";
echo "Name: " . $emp->name . "\n";
echo "Designation: " . $emp->designation . "\n";
echo "Account No: " . $emp->account_no . "\n";
echo "Joining Date: " . $emp->joining_date . "\n";
echo "Salary: " . $emp->getSalary() . "\n";
return;
}
}
echo "Employee with code $code not found.\n";
}
function displaySalary($code) {
global $employeeRecords;
foreach ($employeeRecords as $emp) {
if ($emp->code == $code) {
echo "Salary details for employee $code: \n";
echo "Basic Pay: " . $emp->basic_pay . "\n";
echo "Earnings: " . $emp->earnings . "\n";
echo "Deductions: " . $emp->deduction . "\n";
echo "Net Salary: " . $emp->getSalary() . "\n";
return;
}
}
echo "Employee with code $code not found.\n";
}
function menu() {
do {
echo "\n--- Employee Management System ---\n";
echo "1. Build Master Table\n";
echo "2. Sort All Entries\n";
echo "3. Search an Entry\n";
echo "4. Display Salary\n";
echo "5. Exit\n";
echo "Enter your choice: ";
$choice = trim(fgets(STDIN));
switch ($choice) {
case 1:
buildMasterTable();
break;
case 2:
sortEntries();
break;
case 3:
echo "Enter Employee Code to search: ";
$code = trim(fgets(STDIN));
searchEntry($code);
break;
case 4:
echo "Enter Employee Code to display salary: ";
$code = trim(fgets(STDIN));
displaySalary($code);
break;
case 5:
echo "Exiting...\n";
break;
default:
echo "Invalid choice. Please try again.\n";
break;
}
} while ($choice != 5);
}
// Run the menu function
menu();
?>
OUTPUT-:
2) Define an interface which has methods area( ), volume( ). Define constant PI.
Create a class cylinder which implements this interface and calculate area and
volume. (Hint: Use define())
Solution-:

<?php
interface Shape {
const PI = 3.14159;
public function area();
public function volume();
}
class Cylinder implements Shape {
private $radius;
private $height;
public function __construct($radius, $height) {
$this->radius = $radius;
$this->height = $height;
}
public function area() {
return 2 * Shape::PI * $this->radius * ($this->radius + $this->height);
}
public function volume() {
return Shape::PI * pow($this->radius, 2) * $this->height;
}
}
$cylinder = new Cylinder(5, 10);
echo "Surface Area of Cylinder: " . $cylinder->area() . "\n";
echo "Volume of Cylinder: " . $cylinder->volume() . "\n";
?>
OUTPUT-:
Surface Area of Cylinder: 471.2385
Volume of Cylinder: 785.398

3) Write a Calculator class that can accept two values, then add them, subtract
them, multiply them together, or divide them one request.
Solution-:
<?php

class Calculator {
private $num1;
private $num2;

// Constructor to initialize the two numbers


public function __construct($num1, $num2) {
$this->num1 = $num1;
$this->num2 = $num2;
}

// Method to add the two numbers


public function add() {
return $this->num1 + $this->num2;
}

// Method to subtract the second number from the first


public function subtract() {
return $this->num1 - $this->num2;
}
// Method to multiply the two numbers
public function multiply() {
return $this->num1 * $this->num2;
}

// Method to divide the first number by the second


// Includes check for division by zero
public function divide() {
if ($this->num2 == 0) {
return "Error: Division by zero is not allowed.";
}
return $this->num1 / $this->num2;
}
}

// Example Usage

// Create a new Calculator object with two numbers


$calc = new Calculator(10, 5);

// Perform addition
echo "Addition: " . $calc->add() . "\n";

// Perform subtraction
echo "Subtraction: " . $calc->subtract() . "\n";

// Perform multiplication
echo "Multiplication: " . $calc->multiply() . "\n";

// Perform division
echo "Division: " . $calc->divide() . "\n";

// Division by zero example


$calc_zero = new Calculator(10, 0);
echo "Division by Zero: " . $calc_zero->divide() . "\n";

?>
OUTPUT-:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
Division by Zero: Error: Division by zero is not allowed.
Set B:
1) Create a class named DISTANCE with feet and inches as data
members. The classhas the following member functions:
convert_feet_to_inch() , convert_inch_to_feet() .
Display options using radio button and display conversion on nextpage.
Solution-:
<?php
// Define the DISTANCE class with feet and inches as data members
class DISTANCE {
public $feet;
public $inches;

// Constructor to initialize feet and inches


public function __construct($feet = 0, $inches = 0) {
$this->feet = $feet;
$this->inches = $inches;
}

// Method to convert feet to inches


public function convert_feet_to_inch() {
return $this->feet * 12; // 1 foot = 12 inches
}

// Method to convert inches to feet


public function convert_inch_to_feet() {
return $this->inches / 12; // 1 foot = 12 inches
}
}

// Check if the form is submitted


if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the input values
$feet = isset($_POST['feet']) ? $_POST['feet'] : 0;
$inches = isset($_POST['inches']) ? $_POST['inches'] : 0;
$conversion_type = isset($_POST['conversion_type']) ? $_POST['conversion_type'] : '';

// Create an instance of DISTANCE class


$distance = new DISTANCE($feet, $inches);

$result = "";

// Perform the appropriate conversion based on user selection


if ($conversion_type == 'feet_to_inches') {
$result = $distance->convert_feet_to_inch() . " inches";
} elseif ($conversion_type == 'inches_to_feet') {
$result = $distance->convert_inch_to_feet() . " feet";
}
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Distance Converter</title>
</head>
<body>
<h1>Distance Converter</h1>
<!-- Form to accept feet and inches -->
<form method="POST" action="distance.php">
<label for="feet">Feet:</label>
<input type="number" name="feet" id="feet" value="<?php echo isset($feet) ? $feet : '';
?>" step="any">
<br><br>
<label for="inches">Inches:</label>
<input type="number" name="inches" id="inches" value="<?php echo isset($inches) ?
$inches : ''; ?>" step="any">
<br><br>

<input type="radio" id="feet_to_inches" name="conversion_type"


value="feet_to_inches" <?php echo isset($conversion_type) && $conversion_type ==
'feet_to_inches' ? 'checked' : ''; ?>>
<label for="feet_to_inches">Convert Feet to Inches</label><br>

<input type="radio" id="inches_to_feet" name="conversion_type"


value="inches_to_feet" <?php echo isset($conversion_type) && $conversion_type ==
'inches_to_feet' ? 'checked' : ''; ?>>
<label for="inches_to_feet">Convert Inches to Feet</label><br><br>

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


</form>

<?php if (isset($result) && $result != ""): ?>


<h2>Conversion Result:</h2>
<p><?php echo $result; ?></p>
<?php endif; ?>
</body>
</html>
OUTPUT-:
Conversion Result:
36 inches

2) Write a PHP program to create a class Employee that contains data


members as
Emp_Name, Dept_name , Basic_sal,DA, HRA,TA , IT,PF,PT , GROSS,
DEDUCTION ,NET . It hasmember functions calculate_gross , calculate_deductions ,
Calculate_net_salary . Display pay slip of employee. Create and Initialize members
Emp_Name, Dept_name , Basic_sal of Employee object by using parameterized
constructor.
Solution-:
<?php

class Employee {
// Data members of the class
public $Emp_Name;
public $Dept_name;
public $Basic_sal;
public $DA;
public $HRA;
public $TA;
public $IT;
public $PF;
public $PT;
public $GROSS;
public $DEDUCTION;
public $NET;

// Parameterized constructor to initialize Emp_Name, Dept_name, and Basic_sal


public function __construct($Emp_Name, $Dept_name, $Basic_sal) {
$this->Emp_Name = $Emp_Name;
$this->Dept_name = $Dept_name;
$this->Basic_sal = $Basic_sal;

// Default values for other components of the salary


$this->DA = 0.10 * $Basic_sal; // Dearness Allowance (10% of Basic Salary)
$this->HRA = 0.15 * $Basic_sal; // House Rent Allowance (15% of Basic Salary)
$this->TA = 0.05 * $Basic_sal; // Travel Allowance (5% of Basic Salary)
$this->IT = 0.10 * $Basic_sal; // Income Tax (10% of Basic Salary)
$this->PF = 0.12 * $Basic_sal; // Provident Fund (12% of Basic Salary)
$this->PT = 200; // Professional Tax (Fixed)
}

// Method to calculate the Gross Salary


public function calculate_gross() {
$this->GROSS = $this->Basic_sal + $this->DA + $this->HRA + $this->TA;
}

// Method to calculate total deductions


public function calculate_deductions() {
$this->DEDUCTION = $this->IT + $this->PF + $this->PT;
}

// Method to calculate net salary after deductions


public function calculate_net_salary() {
$this->NET = $this->GROSS - $this->DEDUCTION;
}

// Method to display the pay slip


public function display_pay_slip() {
echo "<h2>Pay Slip of " . $this->Emp_Name . "</h2>";
echo "<p>Department: " . $this->Dept_name . "</p>";
echo "<p>Basic Salary: Rs. " . number_format($this->Basic_sal, 2) . "</p>";
echo "<p>Dearness Allowance (DA): Rs. " . number_format($this->DA, 2) . "</p>";
echo "<p>House Rent Allowance (HRA): Rs. " . number_format($this->HRA, 2) .
"</p>";
echo "<p>Travel Allowance (TA): Rs. " . number_format($this->TA, 2) . "</p>";
echo "<p>Gross Salary: Rs. " . number_format($this->GROSS, 2) . "</p>";
echo "<hr>";
echo "<p>Income Tax (IT): Rs. " . number_format($this->IT, 2) . "</p>";
echo "<p>Provident Fund (PF): Rs. " . number_format($this->PF, 2) . "</p>";
echo "<p>Professional Tax (PT): Rs. " . number_format($this->PT, 2) . "</p>";
echo "<p>Total Deductions: Rs. " . number_format($this->DEDUCTION, 2) . "</p>";
echo "<hr>";
echo "<p><strong>Net Salary: Rs. " . number_format($this->NET, 2) . "</strong></p>";
}
} $employee1 = new Employee("John Doe", "Software Development", 50000);

// Calculate gross salary, deductions, and net salary


$employee1->calculate_gross();
$employee1->calculate_deductions();
$employee1->calculate_net_salary();

// Display the employee's pay slip


$employee1->display_pay_slip();

?>
OUTPUT-:
Pay Slip of John Doe
Department: Software Development
Basic Salary: Rs. 50000.00
Dearness Allowance (DA): Rs. 5000.00
House Rent Allowance (HRA): Rs. 7500.00
Travel Allowance (TA): Rs. 2500.00
Gross Salary: Rs. 65000.00
------------------------------
Income Tax (IT): Rs. 5000.00
Provident Fund (PF): Rs. 6000.00
Professional Tax (PT): Rs. 200.00
Total Deductions: Rs. 11200.00
------------------------------
Net Salary: Rs. 53800.00
Set C:
1) Write a PHP program to create a class article having articleid, name,
articleqty, price.
Write menu driven program to perform following functions :( Use array ofobjects)
i) Display details of all articlespurchased.
ii) Display details of articles whose price exceeds500
iii) Display details of articles whose quantity exceeds50
Solution-:
<?php
// Class Article Definition
class Article {
public $articleid;
public $name;
public $articleqty;
public $price;

// Constructor to initialize values


public function __construct($articleid, $name, $articleqty, $price) {
$this->articleid = $articleid;
$this->name = $name;
$this->articleqty = $articleqty;
$this->price = $price;
}

// Method to display article details


public function display_details() {
echo "Article ID: " . $this->articleid . "<br>";
echo "Name: " . $this->name . "<br>";
echo "Quantity: " . $this->articleqty . "<br>";
echo "Price: Rs. " . $this->price . "<br><br>";
}
}

// Array to hold articles


$articles = array();

// Function to display all articles


function display_all_articles($articles) {
echo "<h3>All Articles Purchased</h3>";
foreach ($articles as $article) {
$article->display_details();
}
}

// Function to display articles with price exceeding 500


function display_articles_price_exceeds_500($articles) {
echo "<h3>Articles Whose Price Exceeds Rs. 500</h3>";
$found = false;
foreach ($articles as $article) {
if ($article->price > 500) {
$article->display_details();
$found = true;
}
}
if (!$found) {
echo "No articles found with price exceeding Rs. 500.<br><br>";
}
}

// Function to display articles with quantity exceeding 50


function display_articles_qty_exceeds_50($articles) {
echo "<h3>Articles Whose Quantity Exceeds 50</h3>";
$found = false;
foreach ($articles as $article) {
if ($article->articleqty > 50) {
$article->display_details();
$found = true;
}
}
if (!$found) {
echo "No articles found with quantity exceeding 50.<br><br>";
}
}

// Main Menu for user input


if ($_SERVER["REQUEST_METHOD"] == "POST") {
$choice = $_POST['choice'];

// Add sample articles to the array


if (empty($articles)) {
$articles[] = new Article(1, "Article 1", 30, 400);
$articles[] = new Article(2, "Article 2", 60, 600);
$articles[] = new Article(3, "Article 3", 120, 700);
$articles[] = new Article(4, "Article 4", 45, 250);
$articles[] = new Article(5, "Article 5", 70, 1000);
}

// Perform actions based on the user's menu choice


switch ($choice) {
case 1:
display_all_articles($articles);
break;
case 2:
display_articles_price_exceeds_500($articles);
break;
case 3:
display_articles_qty_exceeds_50($articles);
break;
default:
echo "Invalid choice. Please select a valid option.<br><br>";
}
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Article Management System</title>
</head>
<body>
<h1>Article Management System</h1>
<form method="POST">
<label for="choice">Select an option:</label><br><br>
<input type="radio" name="choice" value="1" id="option1">
Display all articles purchased<br>
<input type="radio" name="choice" value="2" id="option2">
Display articles with price exceeding Rs. 500<br>
<input type="radio" name="choice" value="3" id="option3">
Display articles with quantity exceeding 50<br><br>
<input type="submit" value="Submit">
</form>

</body>
</html>

2) Write a PHP program to create a class Worker that has data members
as Worker_Name, No_of_Days_worked, Pay_Rate. Create and initialize the
object using default constructor, Parameterized constructor. Also write
necessary member function to calculate and display the salary ofworker.
Solution-:
<?php

class Worker {
// Data members
public $Worker_Name;
public $No_of_Days_worked;
public $Pay_Rate;

// Default constructor
public function __construct() {
$this->Worker_Name = "Unknown Worker";
$this->No_of_Days_worked = 0;
$this->Pay_Rate = 0;
}

// Parameterized constructor
public function __construct($name, $days_worked, $pay_rate) {
$this->Worker_Name = $name;
$this->No_of_Days_worked = $days_worked;
$this->Pay_Rate = $pay_rate;
}

// Member function to calculate and display the salary


public function calculateSalary() {
$salary = $this->No_of_Days_worked * $this->Pay_Rate;
echo "Salary of " . $this->Worker_Name . " is: $" . $salary . "<br>";
}

// Member function to display worker details


public function displayWorkerDetails() {
echo "Worker Name: " . $this->Worker_Name . "<br>";
echo "Number of Days Worked: " . $this->No_of_Days_worked .
"<br>";
echo "Pay Rate: $" . $this->Pay_Rate . " per day<br>";
}
}

// Creating an object using the parameterized constructor


$worker1 = new Worker("John Doe", 20, 100);
$worker1->displayWorkerDetails();
$worker1->calculateSalary();

// Creating an object using the default constructor


$worker2 = new Worker();
$worker2->displayWorkerDetails();
$worker2->calculateSalary();

?>
OUTPUT-:
Worker Name: John Doe
Number of Days Worked: 20
Pay Rate: $100 per day
Salary of John Doe is: $2000

Worker Name: Unknown Worker


Number of Days Worked: 0
Pay Rate: $0 per day
Salary of Unknown Worker is: $0
Assignment 2: To study Web Techniques

Set A:
1) Write PHP program accept name, select your cities you would like to
visit and display selected information on page. (Use multi-valuedparameter),.
Solution-:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get user input
$name = $_POST['name'];
$cities = isset($_POST['cities']) ? $_POST['cities'] : [];

// Display the user's name and selected cities


echo "<h3>Name: " . htmlspecialchars($name) . "</h3>";
echo "<h3>Cities you would like to visit:</h3>";

if (!empty($cities)) {
echo "<ul>";
foreach ($cities as $city) {
echo "<li>" . htmlspecialchars($city) . "</li>";
}
echo "</ul>";
} else {
echo "<p>No cities selected.</p>";
}
} else {
// Display the form
echo '<h2>Select Cities You Would Like to Visit</h2>';
echo '<form method="POST" action="">';
echo 'Name: <input type="text" name="name" required><br><br>';

// Multiple cities selection using checkboxes


echo 'Select Cities: <br>';
echo '<input type="checkbox" name="cities[]" value="New York"> New
York<br>';
echo '<input type="checkbox" name="cities[]" value="Los Angeles"> Los
Angeles<br>';
echo '<input type="checkbox" name="cities[]" value="Paris"> Paris<br>';
echo '<input type="checkbox" name="cities[]" value="Tokyo"> Tokyo<br>';
echo '<input type="checkbox" name="cities[]" value="London">
London<br>';
echo '<br>';
echo '<input type="submit" value="Submit">';
echo '</form>';
}
?>
OUTPUT-:

Name: John Doe


Cities you would like to visit:
- New York
- Tokyo
2) Write PHP program to create student registration form and display
student information. (Use sticky formconcept).
Solution-:
<?php
// Declare variables and set them to empty values
$name = $email = $dob = $gender = $course = $address = "";
$nameErr = $emailErr = $dobErr = $genderErr = $courseErr = $addressErr =
"";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate and sanitize input data
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = htmlspecialchars($_POST["name"]);
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = htmlspecialchars($_POST["email"]);
}

if (empty($_POST["dob"])) {
$dobErr = "Date of Birth is required";
} else {
$dob = htmlspecialchars($_POST["dob"]);
}

if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = $_POST["gender"];
}

if (empty($_POST["course"])) {
$courseErr = "Course selection is required";
} else {
$course = $_POST["course"];
}

if (empty($_POST["address"])) {
$addressErr = "Address is required";
} else {
$address = htmlspecialchars($_POST["address"]);
}
}

// If form is valid, display student information


if (empty($nameErr) && empty($emailErr) && empty($dobErr) &&
empty($genderErr) && empty($courseErr) && empty($addressErr)) {
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "<h2>Student Information</h2>";
echo "<p><strong>Name:</strong> $name</p>";
echo "<p><strong>Email:</strong> $email</p>";
echo "<p><strong>Date of Birth:</strong> $dob</p>";
echo "<p><strong>Gender:</strong> $gender</p>";
echo "<p><strong>Course:</strong> $course</p>";
echo "<p><strong>Address:</strong> $address</p>";
}
} else {
// Display the form with sticky values
echo '<h2>Student Registration Form</h2>';
echo '<form method="POST" action="">';

// Name input field


echo 'Name: <input type="text" name="name" value="' . $name . '">';
echo '<span style="color: red;">' . $nameErr . '</span><br><br>';

// Email input field


echo 'Email: <input type="email" name="email" value="' . $email . '">';
echo '<span style="color: red;">' . $emailErr . '</span><br><br>';

// Date of Birth input field


echo 'Date of Birth: <input type="date" name="dob" value="' . $dob . '">';
echo '<span style="color: red;">' . $dobErr . '</span><br><br>';

// Gender radio buttons


echo 'Gender: <input type="radio" name="gender" value="Male" ' . ($gender
== 'Male' ? 'checked' : '') . '> Male';
echo '<input type="radio" name="gender" value="Female" ' . ($gender ==
'Female' ? 'checked' : '') . '> Female';
echo '<span style="color: red;">' . $genderErr . '</span><br><br>';

// Course dropdown
echo 'Course: <select name="course">';
echo '<option value="">Select a course</option>';
echo '<option value="Computer Science" ' . ($course == 'Computer Science'
? 'selected' : '') . '>Computer Science</option>';
echo '<option value="Mechanical Engineering" ' . ($course == 'Mechanical
Engineering' ? 'selected' : '') . '>Mechanical Engineering</option>';
echo '<option value="Electrical Engineering" ' . ($course == 'Electrical
Engineering' ? 'selected' : '') . '>Electrical Engineering</option>';
echo '</select>';
echo '<span style="color: red;">' . $courseErr . '</span><br><br>';

// Address input field


echo 'Address: <textarea name="address">' . $address . '</textarea>';
echo '<span style="color: red;">' . $addressErr . '</span><br><br>';

// Submit button
echo '<input type="submit" value="Submit">';
echo '</form>';
}
?>
Set B:
1) Write a PHP Script to display Server information in table format
(Use$_SERVER).

Solution-:
<?php
// Start HTML output
echo "<h2>Server Information</h2>";
echo "<table border='1' cellpadding='10' cellspacing='0'>";
echo "<tr><th>Property</th><th>Value</th></tr>";

// Display various server information using $_SERVER

// Server Name
echo "<tr><td><strong>Server Name</strong></td><td>" .
$_SERVER['SERVER_NAME'] . "</td></tr>";

// Server Software
echo "<tr><td><strong>Server Software</strong></td><td>" .
$_SERVER['SERVER_SOFTWARE'] . "</td></tr>";

// Server Protocol
echo "<tr><td><strong>Server Protocol</strong></td><td>" .
$_SERVER['SERVER_PROTOCOL'] . "</td></tr>";

// Document Root
echo "<tr><td><strong>Document Root</strong></td><td>" .
$_SERVER['DOCUMENT_ROOT'] . "</td></tr>";

// PHP Self (Script name)


echo "<tr><td><strong>PHP Self</strong></td><td>" .
$_SERVER['PHP_SELF'] . "</td></tr>";

// Request URI
echo "<tr><td><strong>Request URI</strong></td><td>" .
$_SERVER['REQUEST_URI'] . "</td></tr>";

// Remote Address (Client IP)


echo "<tr><td><strong>Remote Address</strong></td><td>" .
$_SERVER['REMOTE_ADDR'] . "</td></tr>";

// Remote Host (Client Hostname)


echo "<tr><td><strong>Remote Host</strong></td><td>" .
$_SERVER['REMOTE_HOST'] . "</td></tr>";
// Server Port
echo "<tr><td><strong>Server Port</strong></td><td>" .
$_SERVER['SERVER_PORT'] . "</td></tr>";

// Script Filename (Full path of the current script)


echo "<tr><td><strong>Script Filename</strong></td><td>" .
$_SERVER['SCRIPT_FILENAME'] . "</td></tr>";

// Request Method (GET, POST, etc.)


echo "<tr><td><strong>Request Method</strong></td><td>" .
$_SERVER['REQUEST_METHOD'] . "</td></tr>";

// Referer (URL of the previous page)


echo "<tr><td><strong>Referer</strong></td><td>" .
$_SERVER['HTTP_REFERER'] . "</td></tr>";

// User Agent (Browser information)


echo "<tr><td><strong>User Agent</strong></td><td>" .
$_SERVER['HTTP_USER_AGENT'] . "</td></tr>";

echo "</table>";
?>
2) Write a PHP program to accept two strings from user and check
whether entered strings are matching or not. (Use sticky formconcept).
Solution-:
<?php
// Declare variables to store form input values
$string1 = $string2 = "";
$error = $message = "";

// Check if the form has been submitted


if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve the strings from the POST request
$string1 = $_POST['string1'];
$string2 = $_POST['string2'];

// Check if both strings are entered


if (empty($string1) || empty($string2)) {
$error = "Both fields are required!";
} else {
// Check if the strings are matching
if ($string1 === $string2) {
$message = "The strings match!";
} else {
$message = "The strings do not match.";
}
}
}

?>

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

<h2>Enter Two Strings to Check If They Match</h2>

<!-- Display form -->


<form method="POST" action="">
<label for="string1">String 1:</label>
<input type="text" name="string1" value="<?php echo
htmlspecialchars($string1); ?>" required><br><br>

<label for="string2">String 2:</label>


<input type="text" name="string2" value="<?php echo
htmlspecialchars($string2); ?>" required><br><br>

<input type="submit" value="Check Strings">


</form>

<!-- Display error message if strings are empty -->


<?php if ($error != "") { ?>
<p style="color: red;"><?php echo $error; ?></p>
<?php } ?>

<!-- Display message about string match -->


<?php if ($message != "") { ?>
<p><?php echo $message; ?></p>
<?php } ?>

</body>
</html>

OUTPUT-:
Enter Two Strings to Check If They Match
[ String 1: __________ ]
[ String 2: __________ ]
[ Check Strings ]
The strings match!
Assignment 3 – XML

Set A:
1) Write a PHP script to create XML file named“Course.xml”
<Course>
<SYBBA CA>
<Studentname> ....... </Studentname>
<Classname> ...... </Class name>
<percentage> .... </percentage>
</SYBBA CA>
</Course>
Store the details of 5 students who are in SYBBACA.
Solution-:
<?php

// Create a new XML document with the root element <Course>


$xml = new SimpleXMLElement('<Course></Course>');

// Add the <SYBBA CA> element under <Course>


$sybba = $xml->addChild('SYBBA_CA');

// Add details of 5 students


$students = [
["name" => "John Doe", "classname" => "SYBBA CA", "percentage" =>
"85"],
["name" => "Jane Smith", "classname" => "SYBBA CA", "percentage"
=> "90"],
["name" => "Alice Johnson", "classname" => "SYBBA CA",
"percentage" => "88"],
["name" => "Bob Brown", "classname" => "SYBBA CA", "percentage"
=> "92"],
["name" => "Charlie Lee", "classname" => "SYBBA CA", "percentage"
=> "80"],
];

// Loop through each student and add their details to the XML
foreach ($students as $student) {
$studentNode = $sybba->addChild('Student');
$studentNode->addChild('Studentname', $student["name"]);
$studentNode->addChild('Classname', $student["classname"]);
$studentNode->addChild('Percentage', $student["percentage"]);
}

// Save the XML content to a file named "Course.xml"


$xml->asXML('Course.xml');

echo "XML file 'Course.xml' has been created successfully.";


?>
OUTPUT-:
<Course>
<SYBBA_CA>
<Student>
<Studentname>John Doe</Studentname>
<Classname>SYBBA CA</Classname>
<Percentage>85</Percentage>
</Student>
<Student>
<Studentname>Jane Smith</Studentname>
<Classname>SYBBA CA</Classname>
<Percentage>90</Percentage>
</Student>
<Student>
<Studentname>Alice Johnson</Studentname>
<Classname>SYBBA CA</Classname>
<Percentage>88</Percentage>
</Student>
<Student>
<Studentname>Bob Brown</Studentname>
<Classname>SYBBA CA</Classname>
<Percentage>92</Percentage>
</Student>
<Student>
<Studentname>Charlie Lee</Studentname>
<Classname>SYBBA CA</Classname>
<Percentage>80</Percentage>
</Student>
</SYBBA_CA>
</Course>
2) Write PHP script to generate an XML code in the followingformat
<?xml version="1.0" encoding="ISO-8859-1" ?>

<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE> <ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
</CATALOG>
Save the file with name “CD.xml”.

Solution-:
<?php

// Create a new XML document with the declaration and root element
<CATALOG>
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="ISO-
8859-1" ?><CATALOG></CATALOG>');

// Add a <CD> element under the <CATALOG> root


$cd = $xml->addChild('CD');

// Add child elements within the <CD> element


$cd->addChild('TITLE', 'Empire Burlesque');
$cd->addChild('ARTIST', 'Bob Dylan');
$cd->addChild('COUNTRY', 'USA');
$cd->addChild('COMPANY', 'Columbia');
$cd->addChild('PRICE', '10.90');
$cd->addChild('YEAR', '1985');

// Save the generated XML to a file


$xml->asXML('catalog.xml');

// Output the XML content


Header('Content-type: text/xml');
echo $xml->asXML();

echo "XML file 'catalog.xml' has been created successfully.";


?>

OUTPUT-:
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
</CATALOG>
Set B:
1) Write a script to create “cricket.xml” file with multiple elements as
shownbelow: <CricketTeam>
<Team country=”India”>
<player> </player>
<runs> </runs>
<wicket> </wicket>
</Team>
</CricketTeam>
Write a script to add multiple elements in “cricket.xml” file of category,
country=”Australia”.
Solution-:
<?php

// Create a new XML document with the root element <CricketTeam>


$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-
8"?><CricketTeam></CricketTeam>');

// Add a <Team> element for India


$indiaTeam = $xml->addChild('Team');
$indiaTeam->addAttribute('country', 'India');
$indiaTeam->addChild('player', 'Virat Kohli');
$indiaTeam->addChild('runs', '1500');
$indiaTeam->addChild('wicket', '10');

$indiaTeam2 = $xml->addChild('Team');
$indiaTeam2->addAttribute('country', 'India');
$indiaTeam2->addChild('player', 'Rohit Sharma');
$indiaTeam2->addChild('runs', '1400');
$indiaTeam2->addChild('wicket', '15');

// Add a <Team> element for Australia


$australiaTeam = $xml->addChild('Team');
$australiaTeam->addAttribute('country', 'Australia');
$australiaTeam->addChild('player', 'Steve Smith');
$australiaTeam->addChild('runs', '2000');
$australiaTeam->addChild('wicket', '25');

$australiaTeam2 = $xml->addChild('Team');
$australiaTeam2->addAttribute('country', 'Australia');
$australiaTeam2->addChild('player', 'David Warner');
$australiaTeam2->addChild('runs', '1800');
$australiaTeam2->addChild('wicket', '20');

$australiaTeam3 = $xml->addChild('Team');
$australiaTeam3->addAttribute('country', 'Australia');
$australiaTeam3->addChild('player', 'Pat Cummins');
$australiaTeam3->addChild('runs', '1200');
$australiaTeam3->addChild('wicket', '40');

// Save the generated XML content to a file named "cricket.xml"


$xml->asXML('cricket.xml');

// Output success message


echo "XML file 'cricket.xml' has been created and updated successfully.";

?>

OUTPUT-:
<?xml version="1.0" encoding="UTF-8"?>
<CricketTeam>
<Team country="India">
<player>Virat Kohli</player>
<runs>1500</runs>
<wicket>10</wicket>
</Team>
<Team country="India">
<player>Rohit Sharma</player>
<runs>1400</runs>
<wicket>15</wicket>
</Team>
<Team country="Australia">
<player>Steve Smith</player>
<runs>2000</runs>
<wicket>25</wicket>
</Team>
<Team country="Australia">
<player>David Warner</player>
<runs>1800</runs>
<wicket>20</wicket>
</Team>
<Team country="Australia">
<player>Pat Cummins</player>
<runs>1200</runs>
<wicket>40</wicket>
</Team>
</CricketTeam>
2) Write a script to create “breakfast.xml” file with multiple elements as
shownbelow:

<breakfast_menu>
<food>
<name>French Fries</name>
<price>Rs45</price>
<description>Young youths are very much intrested to eat it </description>
<calories>650</calories>
</food>
</breakfast_menu>
Write a script to add multiple elements in “breakfast.xml” file of category,
Juice.
Solution-:
<?php

// Create a new XML document with the root element <breakfast_menu>


$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-
8"?><breakfast_menu></breakfast_menu>');

// Add a <food> element under <breakfast_menu>


$food = $xml->addChild('food');

// Add child elements within <food>


$food->addChild('name', 'French Fries');
$food->addChild('price', 'Rs45');
$food->addChild('description', 'Young youths are very much interested to
eat it');
$food->addChild('calories', '650');

// Add multiple <food> elements for Juice category


$juice1 = $xml->addChild('food');
$juice1->addChild('name', 'Orange Juice');
$juice1->addChild('price', 'Rs40');
$juice1->addChild('description', 'Freshly squeezed orange juice.');
$juice1->addChild('calories', '120');

$juice2 = $xml->addChild('food');
$juice2->addChild('name', 'Apple Juice');
$juice2->addChild('price', 'Rs50');
$juice2->addChild('description', 'Sweet and fresh apple juice.');
$juice2->addChild('calories', '150');

$juice3 = $xml->addChild('food');
$juice3->addChild('name', 'Carrot Juice');
$juice3->addChild('price', 'Rs60');
$juice3->addChild('description', 'Healthy carrot juice for your health.');
$juice3->addChild('calories', '100');

// Save the generated XML content to a file named "breakfast.xml"


$xml->asXML('breakfast.xml');

// Output success message


echo "XML file 'breakfast.xml' has been created and updated successfully.";

?>
OUTPUT-:
<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
<food>

<name>French Fries</name>
<price>Rs45</price>
<description>Young youths are very much interested to eat
it</description>
<calories>650</calories>
</food>
<food>
<name>Orange Juice</name>
<price>Rs40</price>
<description>Freshly squeezed orange juice.</description>
<calories>120</calories>
</food>
<food>
<name>Apple Juice</name>
<price>Rs50</price>
<description>Sweet and fresh apple juice.</description>
<calories>150</calories>
</food>
<food>
<name>Carrot Juice</name>
<price>Rs60</price>
<description>Healthy carrot juice for your health.</description>
<calories>100</calories>
</food>
</breakfast_menu>
Assignment 4: PHP with AJAX
Set A:
1)Write a PHP script using AJAX concept, to check user name and password are valid
or Invalid (use database to store user name andpassword).
Solution-:

<?php
// Database connection settings
$host = 'localhost';
$dbname = 'your_database_name';
$username = 'your_database_user';
$password = 'your_database_password';

// Create PDO instance for database connection


try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Could not connect to the database: " . $e->getMessage());
}

// Check if form data is set


if (isset($_POST['username']) && isset($_POST['password'])) {
$inputUsername = $_POST['username'];
$inputPassword = $_POST['password'];

// Prepare SQL query to fetch user with matching username


$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->execute(['username' => $inputUsername]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($user) {
// User exists, now check the password (if hashed, use password_verify)
if ($user['password'] === $inputPassword) {
echo 'Login successful';
} else {
echo 'Invalid password';
}
} else {
echo 'Username not found';
}
} else {
echo 'Please provide both username and password';
}
?>
if (password_verify($inputPassword, $user['password'])) {
echo 'Login successful';
} else {
echo 'Invalid password';
}
2) Write Ajax program to get book details from XML file when user select a book
name. Create XML file for storing details of book(title, author, year,price).

Solution-:
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<title>Book One</title>
<author>Author One</author>
<year>2021</year>
<price>20.99</price>
</book>
<book>
<title>Book Two</title>
<author>Author Two</author>
<year>2019</year>
<price>15.50</price>
</book>
<book>
<title>Book Three</title>
<author>Author Three</author>
<year>2020</year>
<price>18.75</price>
</book>
<!-- Add more books here as needed -->
</books>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Book Details</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// Function to fetch book details from the XML file
function getBookDetails() {
var selectedBook = $('#bookSelect').val(); // Get selected book title
if (selectedBook) {
$.ajax({
url: 'books.xml', // Path to the XML file
type: 'GET',
dataType: 'xml',
success: function(response) {
// Loop through the XML to find the selected book
$(response).find('book').each(function() {
var title = $(this).find('title').text();
if (title === selectedBook) {
var author = $(this).find('author').text();
var year = $(this).find('year').text();
var price = $(this).find('price').text();

// Display the book details in HTML


$('#bookDetails').html(`
<h3>Book Details:</h3>
<p><strong>Title:</strong> ${title}</p>
<p><strong>Author:</strong> ${author}</p>
<p><strong>Year:</strong> ${year}</p>
<p><strong>Price:</strong> $${price}</p>
`);
}
});
},
error: function() {
alert('Error fetching XML data.');
}
});
}
}
</script>
</head>
<body>

<h2>Select a Book</h2>

<!-- Dropdown to select book -->


<select id="bookSelect" onchange="getBookDetails()">
<option value="">--Select a book--</option>
<option value="Book One">Book One</option>
<option value="Book Two">Book Two</option>
<option value="Book Three">Book Three</option>
</select>

<!-- Container to display book details -->


<div id="bookDetails"></div>

</body>
</html>

You might also like