WBP Practicals Codes
WBP Practicals Codes
1) Write a PHP program to demonstrate Ternary, Null coalescing and Bitwise Operators
<?php
// Ternary Operator Example
echo "Ternary Operator<br>";
$age = 20;
$status = ($age >= 18) ? "Adult" : "Minor";
echo "Age: $age - Status: $status<br><br>";
2) Create a HTML form named “mul formdemo.html” that accepts two numbers from the user.
(Include two labels: 'Enter rst number' and 'Enter second number', along with two textboxes for
number inputs, and four submit bu ons)and Write PHP code to perform basic arithme c
opera ons (addi on, subtrac on, mul plica on, and division) based on the bu on the user
clicks.
<!DOCTYPE html>
<html>
<head>
< tle>Arithme c Opera ons Form</ tle>
</head>
<body>
<h2>Simple Calculator</h2>
<form method="post">
<label>Enter rst number:</label>
<input type="number" name="num1" required><br><br>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$num1 = $_POST["num1"];
$num2 = $_POST["num2"];
$opera on = $_POST["opera on"];
echo "<h2>Result:</h2>";
case "Subtract":
$result = $num1 - $num2;
echo "$num1 - $num2 = $result";
break;
case "Divide":
if ($num2 == 0) {
echo "Error: Division by zero is not allowed.";
} else {
$result = $num1 / $num2;
echo "$num1 ÷ $num2 = $result";
}
break;
default:
echo "Invalid opera on selected.";
}
} else {
echo "Form not submi ed.";
}
?>
</body>
</html>
2
ti
ti
ti
tt
ti
ti
ti
ti
ti
ti
ti
Ques on 2
<?php
echo "<h2>Demonstra ng 'break' Statement</h2>";
echo "<hr>";
2) Create a HTML form named “evenodddemo.html” that accepts a number from the user.(Include a
label 'Enter number', a textbox for number input, and a Submit bu on) and Write a PHP code to
determine whether the given number is odd or even
<!DOCTYPE html>
<html>
<head>
< tle>Even or Odd Checker</ tle>
</head>
<body>
<h2>Check if a Number is Even or Odd</h2>
<form method="post">
<label>Enter number:</label>
<input type="number" name="number" required>
<br><br>
<input type="submit" value="Check">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$num = $_POST["number"];
3
ti
ti
ti
ti
ti
ti
ti
ti
ti
tt
echo "<h3>Result:</h3>";
if ($num % 2 == 0) {
echo "$num is an <strong>Even</strong> number.";
} else {
echo "$num is an <strong>Odd</strong> number.";
}
}
?>
</body>
</html>
Ques on 3
1) Write a PHP program to display even numbers from 1-50 (using for ,while and do..while loop)
<?php
echo "<h2>Even Numbers from 1 to 50 using FOR loop</h2>";
for ($i = 1; $i <= 50; $i++) {
if ($i % 2 == 0) {
echo $i . " ";
}
}
echo "<hr>";
echo "<hr>";
2) Write a PHP program to validate the name, email, password and mobile_no elds of html form
4
ti
fi
<!DOCTYPE html>
<html>
<head>
< tle>Form Valida on</ tle>
</head>
<body>
<h2>Registra on Form</h2>
<?php
// Ini alize variables
$name = $email = $password = $mobile_no = "";
$nameErr = $emailErr = $passwordErr = $mobile_noErr = "";
// Validate Name
if (empty($_POST['name']) || !preg_match("/^[a-zA-Z\s]*$/", $_POST['name'])) {
$nameErr = "Invalid Name: Name should only contain le ers and spaces.";
$isValid = false;
} else {
$name = $_POST['name'];
}
// Validate Email
if (empty($_POST['email']) || ! lter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid Email: Please enter a valid email address.";
$isValid = false;
} else {
$email = $_POST['email'];
}
// Validate Password
if (empty($_POST['password']) || strlen($_POST['password']) < 6) {
$passwordErr = "Invalid Password: Password must be at least 6 characters long.";
$isValid = false;
} else {
$password = $_POST['password'];
}
<label>Email:</label>
<input type="email" name="email" value="<?php echo $email; ?>" required><br>
<span style="color:red"><?php echo $emailErr; ?></span><br><br>
<label>Password:</label>
<input type="password" name="password" required><br>
<span style="color:red"><?php echo $passwordErr; ?></span><br><br>
<label>Mobile Number:</label>
<input type="text" name="mobile_no" value="<?php echo $mobile_no; ?>" required><br>
<span style="color:red"><?php echo $mobile_noErr; ?></span><br><br>
Ques on 4
1) Write a PHP program to display numbers from 1to 10 (using for ,while and do..while loop)
<?php
// Using FOR loop
echo "<h2>Numbers from 1 to 10 using FOR loop</h2>";
for ($i = 1; $i <= 10; $i++) {
echo $i . " ";
}
echo "<hr>";
echo "<hr>";
6
ti
fi
ti
// Using DO...WHILE loop
echo "<h2>Numbers from 1 to 10 using DO...WHILE loop</h2>";
$i = 1;
do {
echo $i . " ";
$i++;
} while ($i <= 10);
?>
2) Create customer form like customer name, address, mobile no, date of birth using di erent form
of input elements and display user inserted values in new PHP form
<!DOCTYPE html>
<html>
<head>
< tle>Customer Informa on Form</ tle>
</head>
<body>
<h2>Customer Informa on Form</h2>
<?php
// Check if the form is submi ed
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Collect and display the values submi ed by the user
$name = $_POST['name'];
$address = $_POST['address'];
$mobile_no = $_POST['mobile_no'];
$dob = $_POST['dob'];
<form method="POST">
<label>Customer Name:</label>
<input type="text" name="name" required><br><br>
<label>Address:</label>
<textarea name="address" rows="4" cols="50" required></textarea><br><br>
<label>Mobile Number:</label>
<input type="text" name="mobile_no" pa ern="^\d{10}$" tle="Please enter a 10-digit mobile
number" required><br><br>
7
ti
ti
ti
tt
ti
ti
ti
tt
tt
tt
ti
ff
<label>Date of Birth:</label>
<input type="date" name="dob" required><br><br>
<?php
}
?>
</body>
</html>
Ques on 5
1) Write a PHP program to display factorial of number (using for ,while and do..while loop).
<!DOCTYPE html>
<html>
<head>
< tle>Factorial using Loops</ tle>
</head>
<body>
<h2>Factorial Calcula on</h2>
<form method="POST">
<label>Enter a number:</label>
<input type="number" name="num" min="0" required>
<input type="submit" value="Calculate Factorial">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$num = $_POST['num'];
2) Write a PHP programs to create database, create table and insert records in a table.
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Check connec on
if ($conn->connect_error) {
die("Connec on failed: " . $conn->connect_error);
}
$conn->close();
?>
Ques on 6
<!DOCTYPE html>
<html>
<head>
< tle>Find Largest of Three Numbers</ tle>
</head>
<body>
<h2>Find the Largest Number</h2>
<form method="POST">
<label>Enter rst number:</label>
<input type="number" name="num1" required><br><br>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$num3 = $_POST['num3'];
2) Write a PHP program to Insert data into employee table and Select data from employee table.
<?php
// DB connec on setup
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "company";
11
ti
ti
ti
// Step 3: Create 'employee' table if not exists
$createTable = "CREATE TABLE IF NOT EXISTS employee (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
designa on VARCHAR(100) NOT NULL,
salary DECIMAL(10,2) NOT NULL
)";
$conn->query($createTable);
$stmt = $conn->prepare("INSERT INTO employee (name, designa on, salary) VALUES (?, ?, ?)");
$stmt->bind_param("ssd", $name, $designa on, $salary);
$stmt->execute();
<!DOCTYPE html>
<html>
<head>
< tle>Employee Data</ tle>
</head>
<body>
<h2>Insert Employee Record</h2>
<form method="POST">
<label>Employee Name:</label>
<input type="text" name="name" required><br><br>
<label>Designa on:</label>
<input type="text" name="designa on" required><br><br>
<label>Salary:</label>
<input type="number" step="0.01" name="salary" required><br><br>
<hr>
<h2>Employee Records</h2>
<?php
// Step 5: Select and display all employee records
$result = $conn->query("SELECT * FROM employee");
12
ti
ti
ti
ti
ti
ti
ti
ti
ti
if ($result->num_rows > 0) {
echo "<table border='1' cellpadding='10'>
<tr>
<th>ID</th><th>Name</th><th>Designa on</th><th>Salary</th>
</tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
<td>{$row['designa on']}</td>
<td>{$row['salary']}</td>
</tr>";
}
echo "</table>";
} else {
echo "No records found.";
}
$conn->close();
?>
</body>
</html>
Ques on 7
<!DOCTYPE html>
<html>
<head>
< tle>Calendar using Switch</ tle>
</head>
<body>
<h2>Calendar Month Days Checker</h2>
<form method="POST">
<label>Enter Month Number (1-12):</label>
<input type="number" name="month" min="1" max="12" required>
<br><br>
<input type="submit" value="Check Days">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$month = $_POST['month'];
switch ($month) {
case 1:
echo "January has 31 days.";
break;
13
ti
ti
ti
ti
ti
case 2:
echo "February has 28 or 29 days (leap year).";
break;
case 3:
echo "March has 31 days.";
break;
case 4:
echo "April has 30 days.";
break;
case 5:
echo "May has 31 days.";
break;
case 6:
echo "June has 30 days.";
break;
case 7:
echo "July has 31 days.";
break;
case 8:
echo "August has 31 days.";
break;
case 9:
echo "September has 30 days.";
break;
case 10:
echo "October has 31 days.";
break;
case 11:
echo "November has 30 days.";
break;
case 12:
echo "December has 31 days.";
break;
default:
echo "Invalid month number!";
}
}
?>
</body>
</html>
2) Write a PHP program to Update and Delete data from employee table
<?php
// Database connec on
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "company";
14
ti
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connec on failed: " . $conn->connect_error);
}
$conn->close();
?>
Ques on 8
1) Write a PHP program crea ng and traversing an Indexed, Associa ve and Mul dimensional
array(using for loop or foreach loop)
<?php
echo "<h2>1. Indexed Array</h2>";
15
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
// Using foreach loop
echo "<br>Using foreach loop:<br>";
foreach ($fruits as $index => $fruit) {
echo "Fruit $index: $fruit<br>";
}
echo "<hr>";
$student = [
"name" => "Amit",
"age" => 21,
"email" => "[email protected]"
];
echo "<hr>";
$employees = [
["id" => 1, "name" => "John", "salary" => 40000],
["id" => 2, "name" => "Alice", "salary" => 45000],
["id" => 3, "name" => "Bob", "salary" => 42000]
];
16
fi
ti
ti
<?php
$to = "[email protected]"; // Replace with recipient's email address
$subject = "Test Email from PHP";
$message = "Hello,\nThis is a test email sent using PHP's mail() func on.";
$headers = "From: [email protected]"; // Replace with a valid sender's email
Ques on 9
1) Write a PHP program to demonstrate Sort func ons for Arrays(sort(),rsort(),asort() , ksort() ,
arsort(),krsort())
<?php
echo "<h2>1. sort() - Indexed array ascending</h2>";
$fruits = ["Banana", "Apple", "Orange", "Mango"];
sort($fruits);
foreach ($fruits as $fruit) {
echo "$fruit<br>";
}
2) Write a PHP program to count total number of rows in the database table
<?php
// Database connec on
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "company"; // Change to your database name
// Create connec on
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connec on
if ($conn->connect_error) {
die("Connec on failed: " . $conn->connect_error);
}
if ($result) {
$row = $result->fetch_assoc();
echo "Total number of rows in '$table' table: " . $row['total'];
} else {
echo "Error: " . $conn->error;
}
$conn->close();
?>
Ques on 10
1) Write a PHP program to demonstrate use of various built-in string func ons
<?php
// De ne a sample string
18
fi
ti
ti
ti
ti
ti
ti
ti
$str = "Welcome to PHP String Func ons";
2) Write a PHP programs to implements Single, Mul level and Mul ple inheritances.
<?php
echo "<h3>Single Inheritance</h3>";
interface Reader {
public func on read();
}
20
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
public func on read() {
echo "Person reads something.<br>";
Ques on 11
1) Write a PHP programs to calculate length of string and count number of words in string without
using string func ons
<?php
// Input string
$input = "This is PHP";
// ==========================
// 1. Calculate length of string without strlen()
// ==========================
$length = 0;
while (isset($input[$length])) {
$length++;
}
// ==========================
// 2. Count number of words without str_word_count()
// ==========================
$wordCount = 0;
$inWord = true;
// Check for a word boundary (not space and was not in a word)
if ($char != ' ' && $inWord) {
$wordCount++;
$inWord = false;
}
// If we hit a space, we are no longer in a word
elseif ($char == ' ') {
$inWord = true;
}
}
// ==========================
// Output
// ==========================
21
ti
ti
ti
ti
ti
ti
echo "Input String: \"$input\"<br>";
echo "Length of string: $length<br>";
echo "Number of words: $wordCount<br>";
?>
<?php
echo "<h2>Func on Overloading (Simulated using __call)</h2>";
class OverloadExample {
public func on __call($name, $arguments) {
if ($name == 'greet') {
$argCount = count($arguments);
if ($argCount == 1) {
echo "Hello, " . $arguments[0] . "!<br>";
} elseif ($argCount == 2) {
echo "Hello, " . $arguments[0] . " and " . $arguments[1] . "!<br>";
} else {
echo "Hello everyone!<br>";
}
}
}
}
// Base class
class Animal {
public func on makeSound() {
echo "Animal makes a sound.<br>";
}
}
22
ti
ti
ti
ti
ti
ti
$dog = new Dog();
$dog->makeSound(); // Dog barks
?>
Ques on 12
1) Write a PHP programs to demonstrate Parameterized func on, Variable func on and Anonymous
func on
<?php
echo "<h2>1. Parameterized Func on</h2>";
// A named func on
func on sayHello() {
echo "Hello from variable func on!<br>";
}
<?php
class Person {
public $name;
public $age;
23
ti
ti
ti
ti
ti
ti
ti
ti
ti
ff
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
// Constructor
public func on __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
Ques on 13
1) Write a PHP programs to draw a rectangle lled with red color and to display text on image
<?php
// Set the content-type to image
header('Content-Type: image/png');
// Free up memory
imagedestroy($image);
?>
<?php
class Person {
public $name;
public $age;
// Constructor
public func on __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
// Create an object
$person = new Person("Alice", 30);
25
fi
fi
fi
ti
ti
ti
ti
ti
ti
ti
// Unserialize the object
$unserializedPerson = unserialize($serializedPerson);
echo "Unserialized Object: ";
$unserializedPerson->display();
echo "<hr>";
?>
Ques on 14
1) Write a PHP program to create a class as “Rectangle” with two proper es length and width.
Calculate area and perimeter of rectangle for two objects
<?php
?>
<?php
// ================== 1. Set a Cookie ========================
// Set a cookie with name 'user', value 'JohnDoe', and expiry me of 1 hour (3600 seconds)
if(!isset($_COOKIE['user'])) {
setcookie("user", "JohnDoe", me() + 3600, "/"); // Cookie will expire in 1 hour
echo "Cookie 'user' is set. <br>";
} else {
echo "Cookie 'user' is already set. <br>";
27
ti
ti
ti
ti
ti
ti
fi
ti
ti
}
?>
Ques on 15
<?php
// Parameterized Constructor
public func on __construct($name, $age, $course) {
$this->name = $name;
$this->age = $age;
$this->course = $course;
echo "Parameterized Constructor called: Person created with custom values.<br>";
}
// Destructor
public func on __destruct() {
echo "Destructor called: Object of Student destroyed.<br>";
}
?>
29
ti
ti
ti
ti
ti
ti
ti
2) Write a PHP program to start session, set session variables, get session variables, modify session
Variables and destroy session.
<?php
// ========================= 1. Start Session ========================
session_start(); // Start the session
30
fi
fi
tti
fi
ti
ti
ti
fi
tti
ft
fi
tti