WBP Solved Practical Final
WBP Solved Practical Final
1) Write a PHP program to demonstrate Ternary, Null coalescing and Bitwise Operators .
<?php
// Ternary Operator
$age = 20;
$status = ($age >= 18) ? "Adult" : "Minor";
echo "Ternary Operator:\n";
echo "Age: $age - Status: $status\n""\n";
// Bitwise Operators
$a = 6; // Binary: 110
$b = 3; // Binary: 011
Form.html
<!DOCTYPE html>
<html>
<head>
<title>Multi Operation Form</title>
</head>
<body>
<h2>Simple Calculator</h2>
<form action="calculate.php" method="post">
<label>Enter first number:</label>
<input type="number" name="num1" required><br><br>
echo "<h2>Result:</h2>";
switch($operation) {
case "Add":
echo "$num1 + $num2 = " . ($num1 + $num2);
break;
case "Subtract":
echo "$num1 - $num2 = " . ($num1 - $num2);
break;
case "Multiply":
echo "$num1 * $num2 = " . ($num1 * $num2);
break;
case "Divide":
if ($num2 != 0) {
echo "$num1 / $num2 = " . ($num1 / $num2);
} else {
echo "Error: Division by zero!";
}
break;
default:
echo "Invalid operation selected.";
}
}
?>
Output:
Form.html
Simple Calculator
Enter first number:
Question 2
1) Write a PHP program to demonstrate Break and Continue Statement
<?php
echo "Demonstrating break and continue in a loop:<br><br>";
if ($i == 8) {
echo "Breaking loop at number 8 using break<br>";
break; // Stops the loop when i = 8
}
Output:
Demonstrating break and continue in a loop:
Number: 1
Number: 2
Number: 3
Skipping number 4 using continue
Number: 5
Number: 6
Number: 7
Breaking loop at number 8 using break
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 button) and
Write a PHP code to determine whether the given number is odd or even
Html
<!-- evenodddemo.html -->
<!DOCTYPE html>
<html>
<head>
<title>Even or Odd Checker</title>
</head>
<body>
<h2>Check Even or Odd</h2>
<form action="evenodd.php" method="post">
<label>Enter number:</label>
<input type="number" name="number" required>
<input type="submit" value="Check">
</form>
</body>
</html>
Php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$num = $_POST['number'];
if ($num % 2 == 0) {
echo "<h3>The number $num is Even.</h3>";
} else {
echo "<h3>The number $num is Odd.</h3>";
}
}
?>
Output:
Question 3
1) Write a PHP program to display even numbers from 1-50 (using for ,while and do..while loop)
<?php
echo "<h3>Using for loop:</h3>";
for ($i = 1; $i <= 50; $i++) {
if ($i % 2 == 0) {
echo "$i ";
}
}
Output:
Using for loop:
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50
2) Write a PHP program to validate the name, email, password and mobile_no fields of html
form
Html:
<!DOCTYPE html>
<html>
<head>
<title>Customer Form</title>
</head>
<body>
<h2>Customer Details Form</h2>
<form action="display_customer.php" method="post">
<label>Customer Name:</label><br>
<input type="text" name="name" pattern= “/^[A-Za-z ]{2,}$/”
required><br><br>
<label>Address:</label><br>
<textarea name="address" rows="4" cols="30"
required></textarea><br><br>
<label>Mobile Number:</label><br>
<input type="tel" name="mobile" pattern="[0-9]{10}"
required><br><br>
<label>Date of Birth:</label><br>
<input type="date" name="dob" required><br><br>
<label>Email Id:</label><br>
<input type="text" name="email" pattern="validate_email.php"
required><br><br>
Email_validate:
Php:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$address = $_POST["address"];
$mobile = $_POST["mobile"];
$dob = $_POST["dob"];
$email = $_POST["email"];
Output:
Customer Details Form
Customer Name:
Address:
Mobile Number:
Date of Birth:
Email Id:
Submit
Question 4
1) Write a PHP program to display numbers from 1to 10 (using for ,while and do..while loop)
<?php
echo "<h3>Using for loop:</h3>";
for ($i = 1; $i <= 10; $i++) {
echo "$i ";
}
2) Create customer form like customer name, address, mobile no, date of birth using different
form of input elements and display user inserted values in new PHP form
Html
<!DOCTYPE html>
<html>
<head>
<title>Customer Form</title>
</head>
<body>
<h2>Customer Details Form</h2>
<form action="display_customer.php" method="post">
<label>Customer Name:</label><br>
<input type="text" name="name" required><br><br>
<label>Address:</label><br>
<textarea name="address" rows="4" cols="30" required></textarea><br><br>
<label>Mobile Number:</label><br>
<input type="tel" name="mobile" pattern="[0-9]{10}" required><br><br>
<label>Date of Birth:</label><br>
<input type="date" name="dob" required><br><br>
Php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$address = $_POST["address"];
$mobile = $_POST["mobile"];
$dob = $_POST["dob"];
Html
Address:
Mobile Number:
Date of Birth:
Submit
php:
Question 5
1) Write a PHP program to display factorial of number (using for ,while and do..while loop).
<?php
$number = 5;
2) Write a PHP programs to create database, create table and insert records in a table.
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE IF NOT EXISTS customerdb";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully or already exists.<br>";
} else {
echo "Error creating database: " . $conn->error;
}
// Create table
$sql = "CREATE TABLE IF NOT EXISTS customers (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(50),
mobile VARCHAR(15)
)";
if ($conn->query($sql) === TRUE) {
echo "Table 'customers' created successfully or already exists.<br>";
} else {
echo "Error creating table: " . $conn->error;
}
// Insert record
$sql = "INSERT INTO customers (name, email, mobile)
VALUES ('John Doe', '[email protected]', '9876543210')";
if ($conn->query($sql) === TRUE) {
echo "New record inserted successfully.";
} else {
echo "Error inserting record: " . $conn->error;
}
$conn->close();
?>
Output:
Database created successfully or already exists.
Table 'customers' created successfully or already exists.
New record inserted successfully.
Question 6
1) Write a PHP program to find largest of three numbers
<?php
$a = 25;
$b = 42;
$c = 18;
Output:
Numbers: A = 25, B = 42, C = 18
Largest number is B = 42
2) Write a PHP program to Insert data into employee table and Select data from employee
table.
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$conn->query("CREATE DATABASE IF NOT EXISTS companydb");
$conn->select_db("companydb");
$conn->close();
?>
Output:
Employee Records:
ID Name Position Salary
Question 7
switch ($month_number) {
case 1:
echo "January";
break;
case 2:
echo "February";
break;
case 3:
echo "March";
break;
case 4:
echo "April";
break;
case 5:
echo "May";
break;
case 6:
echo "June";
break;
case 7:
echo "July";
break;
case 8:
echo "August";
break;
case 9:
echo "September";
break;
case 10:
echo "October";
break;
case 11:
echo "November";
break;
case 12:
echo "December";
break;
default:
echo "Invalid month number! Please enter a number between 1 and 12.";
break;
}
?>
Output:
April
2) Write a PHP program to Update and Delete data from employee table
Updating Data:
<?php
// Create a connection
$conn = mysqli_connect("localhost", "root","","company");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql query to update a record
$sql = "UPDATE emp SET job='Salesman' WHERE ename='Abhijeet' ";
$result=mysqli_query($conn, $sql);
if($result==true){
echo "Record updated successfully";
} else {
echo "Error while updating record: " . mysqli_error($conn);
}
//close connection
mysqli_close($conn);
?>
Delete Data:
<?php
// Create connection
$conn = mysqli_connect("localhost", "root","","company");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql query to delete a record
$sql = "DELETE FROM emp WHERE ename='Abhijeet'";
$result=mysqli_query($conn, $sql);
if($result==true){
echo "Record deleted successfully";
} else {
echo "Error while deleting record: " . mysqli_error($conn);
}
//close connection
mysqli_close($conn);
?>
Output:
Updating Data:
Record updated successfully
Delete Data:
Record deleted successfully
Question 8
<?php
// 1. Indexed Array
$fruits = ["Apple", "Banana", "Mango", "Orange"];
echo "Indexed Array:<br>";
for ($i = 0; $i < count($fruits); $i++) {
echo $fruits[$i] . "<br>";
}
echo "<br>";
// 2. Associative Array
$student = ["name" => "Amit", "age" => 20, "course" => "BMS"];
echo "Associative Array:<br>";
foreach ($student as $key => $value) {
echo "$key : $value<br>";
}
echo "<br>";
// 3. Multidimensional Array
$employees = [
["id" => 1, "name" => "Ravi", "salary" => 30000],
["id" => 2, "name" => "Neha", "salary" => 35000],
["id" => 3, "name" => "Karan", "salary" => 32000]
];
Output:
Indexed Array:
Apple
Banana
Mango
Orange
Associative Array:
name : Amit
age : 20
course : BMS
Multidimensional Array:
id: 1 name: Ravi salary: 30000
id: 2 name: Neha salary: 35000
id: 3 name: Karan salary: 32000
2) Write a PHP program for sending mail
<?php
$to = "[email protected]";
$subject = "Test Email from PHP";
$message = "Hello, this is a test email sent from a PHP script.";
$headers = "From:[email protected]";
if(mail($to, $subject, $message, $headers)) {
echo "Email sent successfully!";
} else {
echo "Failed to send email.";
}
?>
Question 9
1) Write a PHP program to demonstrate Sort functions for Arrays(sort(),rsort(),asort() ,
ksort() , arsort(),krsort())
<?php
// Indexed Array
print_r($numbers);
sort($numbers);
print_r($numbers);
rsort($numbers);
print_r($numbers);
echo "\n";
// Associative Array
$person = [
];
print_r($person);
asort($person);
print_r($person);
ksort($person);
print_r($person);
arsort($person);
print_r($person);
print_r($person);
?>
Output:
2) Write a PHP program to count total number of rows in the database table
<?php
// Create connection
$conn = mysqli_connect("localhost", "root","","company");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT count(*) as total_emp FROM emp ";
$result = mysqli_query($conn, $sql);
//Loop through each row
foreach($result as $res){
echo "Total number of employees are:".$res['total_emp'];
}
mysqli_close($conn);
?>
Output:
Total number of employees are:2
Question 10
<?php
// Original string
$string = "Hello, World! This is PHP string functions demonstration.";
// 7. trim() – Remove whitespace from the beginning and end of the string
$trimmed = " Hello, World! ";
echo "Trimmed string: '" . trim($trimmed) . "<br>";
// 15. strpos() – Find the first occurrence of a substring (again, just for
demonstration)
$position = strpos($string, "PHP");
echo "Position of 'PHP' in string: " . $position . "<br>";
?>
Output:
Length of the string: 57
Position of 'World': 7
Uppercase string: HELLO, WORLD! THIS IS PHP STRING FUNCTIONS DEMONSTRATION.
Lowercase string: hello, world! this is php string functions demonstration.
Substring (from position 7 to 11): World! This
Replace 'World' with 'PHP': Hello, PHP! This is PHP string functions demonstration.
Trimmed string: 'Hello, World!
Capitalize first letter: Hello
Capitalize first letter of each word: Hello World
Reversed string: .noitartsnomed snoitcnuf gnirts PHP si sihT !dlroW ,olleH
Substring from 'World': World! This is PHP string functions demonstration.
Exploded words:
Array ( [0] => Hello, [1] => World! [2] => This [3] => is [4] => PHP [5] => string [6] => functions [7] =>
demonstration. ) Imploded sentence: Hello, World! This is PHP string functions demonstration.
Formatted string: HELLO, WORLD! THIS IS PHP STRING FUNCTIONS DEMONSTRATION.
Position of 'PHP' in string: 22
2) Write a PHP programs to implements Single, Multilevel and Multiple inheritances.
Multiple:
<?php
// First Interface
interface Animal {
public function eat();
}
// Second Interface
interface Pet {
public function play();
}
Single:
<?php
class college {
public $name;
protected $code;
public function __construct($n,$c) {
$this->name = $n;
$this->code = $c;
}
}
class student extends college {
public $sname;
public function __construct($n,$c,$sn) {
parent::__construct($n,$c); // Call parent constructor
$this->sname = $sn;
}
public function display(){
echo "<br>College Name=" .$this->name;
echo "<br>College Code=" .$this->code;
echo "<br>Student Name=" .$this->sname;
}
}
$obj = new student('BVIT','0027','Rajesh');
// This will call the college constructor to set the "name" and "code" property
// and then set the "sname" property within the student constructor
$obj->display();
?>
Multilevel:
class Student1{
public $rollno;
public $name;
function display1(){
echo "<br>Roll no:".$this->rollno;
echo "<br>Student name:".$this->name;
}
}
class Test extends Student1{
public $sub1,$sub2,$sub3;
function display2(){
echo "<br>Mark of subject1:".$this->sub1;
echo "<br>Mark of subject2:".$this->sub2;
echo "<br>Mark of subject3:".$this->sub3;
}
}
class Result extends Test{
public $total;
function __construct($r,$n,$s1,$s2,$s3){
$this->rollno=$r;
$this->name=$n;
$this->sub1=$s1;
$this->sub2=$s2;
$this->sub3=$s3;
}
function display3(){
$this->total=($this->sub1 + $this->sub2+$this->sub3);
echo "<br> Total marks:".$this->total;
echo "<br> Percentage:" .($this->total/3);
}
}
$obj=new Result(3401,'Raj',50,60,70);
$obj->display1();
$obj->display2();
$obj->display3();
?>
Output:
Multiple:
Eating... Playing...
Single:
College Name=BVIT
College Code=0027
Student Name=Rajesh
Multilevel:
Roll no:3401
Student name:Raj
Mark of subject1:50
Mark of subject2:60
Mark of subject3:70
Total marks:180
Percentage:60
Question 11
1) Write a PHP programs to calculate length of string and count number of words in string
without using string functions .
<?php
$str="Hello World!";
for($i=0;isset($str[$i]);$i++){
}
echo "Length of string is:".$i;
$arr=explode(" ",$str);
echo "<br>number of words in a string are:".count($arr);
?>
Output:
Length of string is:12
Number of words in a string are:2
<?php
// Class demonstrating function overriding
class Animal {
// Method in parent class
public function speak() {
echo "Animal speaks\n";
}
}
echo "\n";
<?php
// Creates shape class
class shape{
// __call is magic function which accepts function name and arguments
function __call($name_of_function, $arguments){
// It will check the function name
if($name_of_function == 'area'){
switch (count($arguments)){
//If there is only one argument then it returns area of circle
case 1:
return (3.14 * $arguments[0]*$arguments[0]);
break;
//If there are two arguments then it returns area of rectangle
case 2:
return ($arguments[0]*$arguments[1]);
break;
}
}
}
}
//creating a object of shape class
$obj = new Shape();
//calling area method for circle
echo ("<br> Area of circle is:".$obj->area(2));
//calling area method for rectangle
echo ("<br> Area of rectangle is:".$obj->area(4,2));
?>
Output:
Animal speaks Dog barks Called method: add Arguments passed: 10, 20 Called method: multiply
Arguments passed: 5, 4
Overloading:
Area of circle is:12.56
Area of rectangle is:8
Question 12
1) Write a PHP programs to demonstrate Parameterized function, Variable function and <?
php
echo "<h3>1. Parameterized Function</h3>";
// --------------------------------------
echo "<h3>2. Variable Function</h3>";
function greet($name) {
echo "Hello, $name! Welcome to PHP Variable Functions.<br>";
}
// --------------------------------------
$x = 15;
$y = 25;
1. Parameterized Function
Multiplication is: 20
2. Variable Function
Hello, Alice! Welcome to PHP Variable Functions.
3. Anonymous Function (with Closure)
Sum using anonymous function (closure): 40
2) Write PHP program for cloning of an object
<?php
class Car {
public $brand;
public function __construct($brand) {
$this->brand = $brand;
}
}
$car1 = new Car("Toyota");
$car2 = clone $car1; // Cloning the object
$car2->brand = "Honda"; // Changing the cloned object's property
echo $car1->brand; // Output: Toyota
echo $car2->brand; // Output: Honda
?>
Output:
ToyotaHonda
Question 13
1) Write a PHP programs to draw a rectangle filled with red color and to display text on
image
<?php
// Ensure no output before headers
ob_clean();
// Allocate colors
$red = imagecolorallocate($image, 255, 0, 0); // Red background
$white = imagecolorallocate($image, 255, 255, 255); // White text
// Draw text
imagestring($image, 5, 80, 60, "Hello, Image!", $white);
// Output image
imagepng($image);
// Free up memory
imagedestroy($image);
?>
<?php
class Student {
public $name;
public $age;
$this->name = $name;
$this->age = $age;
// Create an object
echo "<h3>Serialization</h3>";
$serialized = serialize($student);
$unserialized = unserialize($serialized);
echo "<h3>Introspection</h3>";
echo "Methods:<br>";
print_r(get_class_methods($student));
echo "<br><br>";
echo "Properties:<br>";
print_r(get_object_vars($student));
?>
Output:
Serialization
Serialized Data:
O:7:"Student":2:{s:4:"name";s:5:"Alice";s:3:"age";i:22;}
Unserialized Object:
Name: Alice
Age: 22
Introspection
Class Name: Student
Methods:
Array ( [0] => __construct [1] => greet )
Properties:
Array ( [name] => Alice [age] => 22 )
Question 14
1) Write a PHP program to create a class as “Rectangle” with two properties length and
width. Calculate area and perimeter of rectangle for two objects
<?php
//Create a class as “Rectangle” with two properties length & width. Calculate perimeter and area of
rectangle.
class Rectangle{
//Declare properties
public $length=0;
public $width=0;
//method to set values to properties
function setdata($l,$w){
$this->length=$l;
$this->width=$w;
}
//method to calculate the perimeter
function calculatePerimeter(){
echo "Perimeter of rectangle is:".(2*($this->length+$this->width));
}
//method to calculate the area of rectangle
function calculateArea(){
echo "<br>Area of rectangle is:".($this->length*$this->width);
}
}
//Create object of rectangle class
$obj1=new Rectangle;
//call the object methods
$obj1->setdata(20,30);
$obj1->calculatePerimeter();
$obj1->calculateArea();
?>
Output:
Perimeter of rectangle is:100
Area of rectangle is:600
2) Write a PHP program to create access, modify and delete a cookie.
Create cookie:
<html>
<body>
<?php
$cookie_name = "user";
$cookie_value = "Amit Patil";
setcookie ($cookie_name, $cookie_value, time () + (86400*30),"/"); // 86400 = 1 day
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named " . $cookie_name. " is not set!";
}
else {
echo "Cookie " . $cookie_name . " is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
<p> <b> Note:</b> You might have to reload the page to see the value of the cookie.
</p>
</body>
</html>
Modify Cookie:
<?php
//To modify a cookie, just set (again) the cookie using the setcookie() function
$cookie_name = "user";
$cookie_value = "Rohit Mane";
setcookie($cookie_name, $cookie_value, time() + (86400*30), "/"); // 86400 = 1 day
if(!isset($_COOKIE[$cookie_name])){
echo "Cookie named " . $cookie_name . " is not set!";
}
else{
echo "Cookie " . $cookie_name . " is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
Delete a cookie:
<?php
//To delete a cookie, use the setcookie () function with an expiration date in the past
setcookie("user"," ",0);
echo "Cookie user is deleted";
?>
Output:
Note: You might have to reload the page to see the value of the cookie.
Question 15
1) Write a PHP programs to demonstrate default constructor, parameterized constructor
and destructor
Default Constructor:
<?php
class student{
//declare properties
public $rollno;
public $name;
//This is initializing the object properties
public function __construct(){
$this->rollno=10;
$this->name='Raj';
}
//method to display the student data
public function display(){
echo "<br> Rollno:".$this->rollno;
echo "<br> Student name:".$this->name;
}
}
//create a new object of student class
$s1=new student();
//call object method
$s1->display();
?>
Output:
Rollno:10
Student name:Raj
Parameterized Constructor:
<?php
class student{
//declare properties
public $rollno;
public $name;
//This is initializing the object properties
public function __construct($r,$n){
$this->rollno=$r;
$this->name=$n;
}
//method to display the student data
public function display(){
echo "<br> Rollno:".$this->rollno;
echo "<br> Student name:".$this->name;
}
}
//create a new object of student class
$s1=new student(10,'Raj');
//call object method
$s1->display();
$s2=new student(11,'Amit');
$s2->display();
?>
Destructor:
<?php
class student{
//declare properties
public $rollno;
public $name;
//This is initializing the object properties
public function __construct($r,$n) {
$this->rollno=$r;
$this->name=$n;
}
//method to display the student data
public function display(){
echo "<br>Rollno:".$this->rollno;
echo "<br>Student name:".$this->name;
}
//clean up object resources
public function __destruct() {
echo "<br>Destructor is called..";
}
}
//create a new object of student class
$s1=new student(10,'Raj');
//call object method
$s1->display();
$s2=new student(11,'Amit');
$s2->display();
?>
Output:
Rollno:10
Student name:Raj
Rollno:11
Student name:Amit
Destructor is called..
Destructor is called..
2) Write a PHP program to start session, set session variables, get session variables, modify
session Variables and destroy session
<?php
<? php
session_start ();
?>
<?php
// display session variables that were set on previous page
echo "<br>Favorite color is: " .$_SESSION["favcolor"];
echo "<br>Favorite animal is: " .$_SESSION["favanimal"];
?>
<?php
session_start();
?>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
echo "Session variable is modified.";
?>
3. To destroy Session:
<?php
session_start();
?>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
echo "Session variables are destroyed.";
?>
Output: