1. Create a PHP program using switch to print a grade for marks input (A, B, C, Fail).
<!DOCTYPE html>
<html>
<body>
<form method="post">
Enter Marks: <input type="number" name="marks">
<input type="submit" value="Check Grade">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$marks = $_POST["marks"];
switch (true) {
case ($marks >= 75):
echo "Grade: A";
break;
case ($marks >= 60):
echo "Grade: B";
break;
case ($marks >= 40):
echo "Grade: C";
break;
default:
echo "Grade: Fail";
}
}
?>
</body>
</html>
2. Use while loop to sum the first 10 even numbers.
<?php
$count = 0;
$num = 2;
$sum = 0;
while ($count < 10) {
$sum += $num;
$num += 2;
$count++;
}
echo "Sum of first 10 even numbers: $sum";
?>
3. Write PHP Script to display sum of digit of entered number.
<!DOCTYPE html>
<html>
<body>
<form method="post">
Enter a number: <input type="number" name="num">
<input type="submit" value="Find Sum of Digits">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$num = $_POST["num"];
$sum = 0;
while ($num > 0) {
$sum += $num % 10;
$num = (int)($num / 10);
}
echo "Sum of digits: $sum";
}
?>
</body>
</html>
4. Write a PHP program to display multiplication table of number ‘n’.
<!DOCTYPE html>
<html>
<body>
<form method="post">
Enter a number: <input type="number" name="num">
<input type="submit" value="Show Table">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$n = $_POST["num"];
echo "<h3>Multiplication Table of $n</h3>";
for ($i = 1; $i <= 10; $i++) {
echo "$n x $i = " . ($n * $i) . "<br>";
}
}
?>
</body>
</html>
5. Write a PHP program to display multiplication table of 1 to 5
<!DOCTYPE html>
<html>
<body>
<h3>Multiplication Tables from 1 to 5</h3>
<table border="1" cellpadding="10">
<tr>
<?php
for ($n = 1; $n <= 5; $n++) {
echo "<th>Table of $n</th>";
}
?>
</tr>
<?php
for ($i = 1; $i <= 10; $i++) {
echo "<tr>";
for ($n = 1; $n <= 5; $n++) {
echo "<td>$n x $i = " . ($n * $i) . "</td>";
}
echo "</tr>";
}
?>
</table>
</body>
</html>
6. Write a foreach loop to print values of an indexed and associative array.
<?php
// Indexed array
$colors = ["Red", "Green", "Blue"];
echo "<h3>Indexed Array:</h3>";
foreach ($colors as $color) {
echo "$color<br>";
}
// Associative array
$student = ["name" => "Shravan", "age" => 21, "course" => "Computer Engineering"];
echo "<h3>Associative Array:</h3>";
foreach ($student as $key => $value) {
echo "$key: $value<br>";
}
?>
7. Create an associative array for student names and grades, display them using a loop.
<!DOCTYPE html>
<html>
<body>
<h3>Student Grades</h3>
<table border="1" cellpadding="10">
<tr>
<th>Student Name</th>
<th>Grade</th>
</tr>
<?php
$students = [
"Shravan" => "A",
"Priya" => "B",
"Amit" => "C",
"Neha" => "A+"
];
foreach ($students as $name => $grade) {
echo "<tr><td>$name</td><td>$grade</td></tr>";
}
?>
</table>
</body>
</html>
8. Write a program using multidimensional arrays to store student records (Name, Roll
No, Marks) and print them.
<!DOCTYPE html>
<html>
<body>
<h3>Student Records</h3>
<table border="1" cellpadding="10">
<tr>
<th>Name</th>
<th>Roll No</th>
<th>Marks</th>
</tr>
<?php
$students = [
["name" => "Shravan", "roll_no" => "101", "marks" => 85],
["name" => "Priya", "roll_no" => "102", "marks" => 78],
["name" => "Amit", "roll_no" => "103", "marks" => 92],
["name" => "Neha", "roll_no" => "104", "marks" => 88]
];
foreach ($students as $student) {
echo "<tr><td>" . $student['name'] . "</td><td>" . $student['roll_no'] . "</td><td>" .
$student['marks'] . "</td></tr>";
}
?>
</table>
</body>
</html>
9. Write a program using multidimensional arrays to store user records (Name, email id,
mobile no and address) and print them.
<!DOCTYPE html>
<html>
<body>
<h3>Enter User Records</h3>
<form method="post">
Name: <input type="text" name="name" required><br><br>
Email: <input type="email" name="email" required><br><br>
Mobile No: <input type="text" name="mobile" required><br><br>
Address: <textarea name="address" required></textarea><br><br>
<input type="submit" value="Submit">
</form>
<h3>User Records</h3>
<table border="1" cellpadding="10">
<tr>
<th>Name</th>
<th>Email ID</th>
<th>Mobile No</th>
<th>Address</th>
</tr>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$users = [];
// Add submitted user data to the multidimensional array
$users[] = [
"name" => $_POST["name"],
"email" => $_POST["email"],
"mobile" => $_POST["mobile"],
"address" => $_POST["address"]
];
// Display the records
foreach ($users as $user) {
echo "<tr><td>" . $user['name'] . "</td><td>" . $user['email'] . "</td><td>" .
$user['mobile'] . "</td><td>" . $user['address'] . "</td></tr>";
}
}
?>
</table>
</body>
</html>
10. Write a PHP program to calculate the length of a string and to count words without using
str_word_count().
<!DOCTYPE html>
<html>
<body>
<form method="post">
Enter a string: <input type="text" name="text" required>
<input type="submit" value="Submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$text = $_POST["text"];
// Calculate the length of the string without using strlen
$length = 0;
foreach (str_split($text) as $char) {
$length++;
}
// Count the words without using str_word_count
$word_count = 0;
$in_word = false;
for ($i = 0; $i < $length; $i++) {
if ($text[$i] != ' ') { // Check if the character is not a space
if (!$in_word) {
$word_count++; // We found a new word
$in_word = true;
}
} else {
$in_word = false; // We are now outside a word
}
}
echo "Length of the string: $length<br>";
echo "Number of words: $word_count<br>";
}
?>
</body>
</html>
11. Write a parameterized function to calculate the sum of two numbers.
<!DOCTYPE html>
<html>
<body>
<form method="post">
Enter first number: <input type="number" name="num1" required><br><br>
Enter second number: <input type="number" name="num2" required><br><br>
<input type="submit" value="Calculate Sum">
</form>
<?php
function calculateSum($a, $b) {
return $a + $b;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$n1 = $_POST["num1"];
$n2 = $_POST["num2"];
$sum = calculateSum($n1, $n2);
echo "<h3>Sum: $sum</h3>";
}
?>
</body>
</html>
12. Implement an anonymous function to print a string.
<?php
$message = function($text) {
echo $text;
};
$message("Hello, this is an anonymous function!");
?>
13. Implement single inheritance in PHP (parent class: student and child class: Test1) and
Display details of student with test result.
<?php
// Parent class
class Student {
public $name;
public $roll;
public function setDetails($name, $roll) {
$this->name = $name;
$this->roll = $roll;
}
public function displayDetails() {
echo "Name: $this->name<br>";
echo "Roll No: $this->roll<br>";
}
}
// Child class
class Test1 extends Student {
public $marks;
public function setMarks($marks) {
$this->marks = $marks;
}
public function displayResult() {
$this->displayDetails();
echo "Marks: $this->marks<br>";
}
}
// Create object and call methods
$student1 = new Test1();
$student1->setDetails("Shravan", "101");
$student1->setMarks(88);
$student1->displayResult();
?>
14. Implement multilevel inheritance in PHP (parent class: student child class:
Testsresult) and Display result of student for two class test percentage and average of
test1 and test2 subject wise.
<!DOCTYPE html>
<html>
<body>
<h3>Enter Student Details & Marks</h3>
<form method="post">
Name: <input type="text" name="name" required><br><br>
Roll No: <input type="text" name="roll" required><br><br>
<h4>Test 1 Marks</h4>
Math: <input type="number" name="test1_math" required><br>
Science: <input type="number" name="test1_science" required><br>
English: <input type="number" name="test1_english"
required><br><br>
<h4>Test 2 Marks</h4>
Math: <input type="number" name="test2_math" required><br>
Science: <input type="number" name="test2_science" required><br>
English: <input type="number" name="test2_english"
required><br><br>
<input type="submit" value="Show Result">
</form>
<?php
// Parent class
class Student {
public $name, $roll;
public function setStudent($name, $roll) {
$this->name = $name;
$this->roll = $roll;
}
public function displayStudent() {
echo "<h3>Student Result</h3>";
echo "Name: $this->name<br>";
echo "Roll No: $this->roll<br>";
}
}
// Child class
class Tests extends Student {
public $test1 = [], $test2 = [];
public function setMarks($t1, $t2) {
$this->test1 = $t1;
$this->test2 = $t2;
}
}
// Grandchild class
class Result extends Tests {
public function displayResult() {
$this->displayStudent();
echo "<h4>Subject-wise Marks and Average</h4>";
echo "<table border='1' cellpadding='10'>
<tr>
<th>Subject</th>
<th>Test 1</th>
<th>Test 2</th>
<th>Average</th>
</tr>";
$total = 0;
$subjects = array_keys($this->test1);
foreach ($subjects as $subject) {
$mark1 = $this->test1[$subject];
$mark2 = $this->test2[$subject];
$avg = ($mark1 + $mark2) / 2;
$total += $mark1 + $mark2;
echo "<tr>
<td>$subject</td>
<td>$mark1</td>
<td>$mark2</td>
<td>$avg</td>
</tr>";
}
$percentage = $total / (count($subjects) * 2);
echo "</table><br><strong>Overall Percentage: $percentage
%</strong>";
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$roll = $_POST["roll"];
$test1 = [
"Math" => $_POST["test1_math"],
"Science" => $_POST["test1_science"],
"English" => $_POST["test1_english"]
];
$test2 = [
"Math" => $_POST["test2_math"],
"Science" => $_POST["test2_science"],
"English" => $_POST["test2_english"]
];
$student = new Result();
$student->setStudent($name, $roll);
$student->setMarks($test1, $test2);
$student->displayResult();
}
?>
</body>
</html>
15. Write a PHP script to demonstrate any five-class introspection using
<!DOCTYPE html>
<html>
<body>
<?php
class Person {
public $name = "Default";
public $age = 0;
function greet() {
echo "Hello!";
}
}
class Student extends Person {
public $roll = 101;
function study() {
echo "Studying...";
}
}
$obj = new Student();
// 1. Check if class exists
if (class_exists("Student")) {
echo "Class 'Student' exists.<br>";
}
// 2. Get methods of class
echo "<br>Methods in Student:<br>";
print_r(get_class_methods("Student"));
// 3. Get properties of class
echo "<br><br>Properties in Student:<br>";
print_r(get_class_vars("Student"));
// 4. Get parent class
echo "<br><br>Parent class of Student:<br>";
echo get_parent_class($obj);
// 5. Check if method exists
echo "<br><br>Does method 'study' exist in Student?<br>";
echo method_exists($obj, "study") ? "Yes" : "No";
?>
</body>
</html>
16. Create a class product with data members id, name and price. Consider that
customer bought multiple products. Then Calculate the total price of products
purchased. Use constructor
<?php
class Product {
public $id, $name, $price;
public function __construct($id, $name, $price) {
$this->id = $id;
$this->name = $name;
$this->price = $price;
}
public function display() {
echo "ID: $this->id | Name: $this->name | Price: ₹$this->price<br>";
}
}
// Array of purchased products
$products = [
new Product(1, "Mouse", 500),
new Product(2, "Keyboard", 800),
new Product(3, "Monitor", 7000)
];
$total = 0;
echo "<h3>Purchased Products:</h3>";
foreach ($products as $p) {
$p->display();
$total += $p->price;
}
echo "<br><strong>Total Price: ₹$total</strong>";
?>
17. Write a program to serialize and unserialize an array/object.
<!DOCTYPE html>
<html>
<body>
<?php
// Array serialization
$arr = ["name" => "Shravan", "age" => 21, "city" => "Goa"];
$serializedArr = serialize($arr);
echo "Serialized Array:<br>$serializedArr<br>";
$unserializedArr = unserialize($serializedArr);
echo "<br>Unserialized Array:<br>";
print_r($unserializedArr);
// Object serialization
class Student {
public $name, $roll;
function __construct($name, $roll) {
$this->name = $name;
$this->roll = $roll;
}
}
$student = new Student("Amit", 102);
$serializedObj = serialize($student);
echo "<br>Serialized Object:<br>$serializedObj<br>";
$unserializedObj = unserialize($serializedObj);
echo "<br>Unserialized Object:<br>";
echo "Name: {$unserializedObj->name}, Roll: {$unserializedObj->roll}";
?>
</body>
</html>
18. Design a form for user registration and validate fields like email, password, and phone
using PHP.
<!DOCTYPE html>
<html>
<body>
<h3>User Registration Form</h3>
<?php
// Define error messages
$emailErr = $passwordErr = $phoneErr = "";
$email = $password = $phone = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate Email
if (empty($_POST["email"])) {
$emailErr = "Email is required.";
} elseif (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format.";
} else {
$email = $_POST["email"];
}
// Validate Password
if (empty($_POST["password"])) {
$passwordErr = "Password is required.";
} elseif (strlen($_POST["password"]) < 6) {
$passwordErr = "Password must be at least 6 characters.";
} else {
$password = $_POST["password"];
}
// Validate Phone
if (empty($_POST["phone"])) {
$phoneErr = "Phone number is required.";
} elseif (!preg_match("/^[0-9]{10}$/", $_POST["phone"])) {
$phoneErr = "Invalid phone number. It should be 10 digits.";
} else {
$phone = $_POST["phone"];
}
// If there are no errors, process the registration
if ($emailErr == "" && $passwordErr == "" && $phoneErr == "") {
echo "<h4>Registration Successful!</h4>";
echo "Email: $email<br>";
echo "Phone: $phone<br>";
}
}
?>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Email: <input type="text" name="email" value="<?php echo
$email;?>">
<span style="color: red;"><?php echo $emailErr;?></span><br><br>
Password: <input type="password" name="password" value="<?php
echo $password;?>">
<span style="color: red;"><?php echo $passwordErr;?
></span><br><br>
Phone: <input type="text" name="phone" value="<?php echo
$phone;?>">
<span style="color: red;"><?php echo $phoneErr;?></span><br><br>
<input type="submit" value="Register">
</form>
</body>
</html>
19. Design a form for user registration and retrieve information on successful submission using
PHP.
20. Develop a PHP application to enter student data into a MySQL database. Retrieve and
display data from the database in tabular form. Update a record in the database. Delete a
specific record from the database.
21. Develop a PHP application to enter student data into a MySQL database. Retrieve and
display data from the database in tabular form. Delete a specific record from the database.
<!DOCTYPE html>
<html>
<body>
<h3>Student Data Management</h3>
<?php
// Database connection
$servername = "localhost";
$username = "root"; // Use your database username
$password = ""; // Use your database 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);
}
// Insert Student Data
if ($_SERVER["REQUEST_METHOD"] == "POST" &&
isset($_POST['add_student'])) {
$name = $_POST['name'];
$roll_no = $_POST['roll_no'];
$email = $_POST['email'];
$sql = "INSERT INTO students (name, roll_no, email) VALUES
('$name', '$roll_no', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully.<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
// Update Student Data
if ($_SERVER["REQUEST_METHOD"] == "POST" &&
isset($_POST['update_student'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$roll_no = $_POST['roll_no'];
$email = $_POST['email'];
$sql = "UPDATE students SET name='$name', roll_no='$roll_no',
email='$email' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully.<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
// Delete Student Data
if (isset($_GET['delete'])) {
$id = $_GET['delete'];
$sql = "DELETE FROM students WHERE id=$id";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully.<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
// Display Students
$sql = "SELECT * FROM students";
$result = $conn->query($sql);
echo "<h3>Student Records:</h3>";
echo "<table border='1' cellpadding='10'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Roll No</th>
<th>Email</th>
<th>Action</th>
</tr>";
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" . $row['id'] . "</td>
<td>" . $row['name'] . "</td>
<td>" . $row['roll_no'] . "</td>
<td>" . $row['email'] . "</td>
<td>
<a href='?edit=" . $row['id'] . "'>Edit</a> |
<a href='?delete=" . $row['id'] . "'>Delete</a>
</td>
</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
<h3>Add New Student</h3>
<form method="post">
Name: <input type="text" name="name" required><br><br>
Roll No: <input type="text" name="roll_no" required><br><br>
Email: <input type="text" name="email" required><br><br>
<input type="submit" name="add_student" value="Add Student">
</form>
<?php
// Edit Student Form
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM students WHERE id=$id";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo "<h3>Edit Student</h3>
<form method='post'>
<input type='hidden' name='id' value='" . $row['id'] .
"'>
Name: <input type='text' name='name' value='" .
$row['name'] . "' required><br><br>
Roll No: <input type='text' name='roll_no' value='" .
$row['roll_no'] . "' required><br><br>
Email: <input type='text' name='email' value='" .
$row['email'] . "' required><br><br>
<input type='submit' name='update_student'
value='Update Student'>
</form>";
}
?>
</body>
</html>
22.