0% found this document useful (0 votes)
28 views30 pages

WBP Practicals Codes

The document contains multiple PHP programming tasks including examples of operators, form handling for arithmetic operations, validation of user input, and displaying numbers and factorials using various loops. It demonstrates the use of HTML forms to collect user input and PHP to process and validate that input. Additionally, it covers control statements like break and continue, as well as the implementation of even/odd checks and customer information forms.

Uploaded by

Mayank Naik
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)
28 views30 pages

WBP Practicals Codes

The document contains multiple PHP programming tasks including examples of operators, form handling for arithmetic operations, validation of user input, and displaying numbers and factorials using various loops. It demonstrates the use of HTML forms to collect user input and PHP to process and validate that input. Additionally, it covers control statements like break and continue, as well as the implementation of even/odd checks and customer information forms.

Uploaded by

Mayank Naik
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/ 30

Ques on 1

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>";

// Null Coalescing Operator Example (PHP 7+)


echo "Null Coalescing Operator<br>";
$userInput = null;
$defaultName = "Guest";
$name = $userInput ?? $defaultName; // returns $userInput if not null, otherwise $defaultName
echo "Name: $name<br><br>";

// Bitwise Operators Example


echo "Bitwise Operators<br>";
$a = 5; // Binary: 0101
$b = 3; // Binary: 0011

echo "a = $a, b = $b<br>";


echo "a & b = " . ($a & $b) . " (AND)<br>"; // 0101 & 0011 = 0001 = 1
echo "a | b = " . ($a | $b) . " (OR)<br>"; // 0101 | 0011 = 0111 = 7
echo "a ^ b = " . ($a ^ $b) . " (XOR)<br>"; // 0101 ^ 0011 = 0110 = 6
echo "~a = " . (~$a) . " (NOT)<br>"; // ~0101 = ...1010 = -6 (two's complement)
echo "a << 1 = " . ($a << 1) . " (Le Shi )<br>"; // 0101 << 1 = 1010 = 10
echo "a >> 1 = " . ($a >> 1) . " (Right Shi )<br>"; // 0101 >> 1 = 0010 = 2
?>

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>

<label>Enter second number:</label>


1
ti
ti
ti
ti
ti
fi
ti
fi
ti
ft
ti
ft
ti
ft
tt
ti
ti
tt
ti
<input type="number" name="num2" required><br><br>

<input type="submit" name="opera on" value="Add">


<input type="submit" name="opera on" value="Subtract">
<input type="submit" name="opera on" value="Mul ply">
<input type="submit" name="opera on" value="Divide">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$num1 = $_POST["num1"];
$num2 = $_POST["num2"];
$opera on = $_POST["opera on"];

echo "<h2>Result:</h2>";

switch ($opera on) {


case "Add":
$result = $num1 + $num2;
echo "$num1 + $num2 = $result";
break;

case "Subtract":
$result = $num1 - $num2;
echo "$num1 - $num2 = $result";
break;

case "Mul ply":


$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

1) Write a PHP program to demonstrate Break and Con nue Statement

<?php
echo "<h2>Demonstra ng 'break' Statement</h2>";

for ($i = 1; $i <= 10; $i++) {


if ($i == 6) {
echo "Loop stopped at i = $i using break.<br>";
break; // exits the loop when i = 6
}
echo "i = $i<br>";
}

echo "<hr>";

echo "<h2>Demonstra ng 'con nue' Statement</h2>";

for ($i = 1; $i <= 10; $i++) {


if ($i == 5 || $i == 7) {
// Skip the current itera on when i = 5 or i = 7
con nue;
}
echo "i = $i<br>";
}
?>

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 "<h2>Even Numbers from 1 to 50 using WHILE loop</h2>";


$i = 1;
while ($i <= 50) {
if ($i % 2 == 0) {
echo $i . " ";
}
$i++;
}

echo "<hr>";

echo "<h2>Even Numbers from 1 to 50 using DO...WHILE loop</h2>";


$i = 1;
do {
if ($i % 2 == 0) {
echo $i . " ";
}
$i++;
} while ($i <= 50);
?>

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 = "";

// Check if the form is submi ed


if ($_SERVER["REQUEST_METHOD"] == "POST") {
$isValid = true;

// 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'];
}

// Validate Mobile Number


if (empty($_POST['mobile_no']) || !preg_match("/^[0-9]{10}$/", $_POST['mobile_no'])) {
$mobile_noErr = "Invalid Mobile Number: Mobile number must be exactly 10 digits.";
$isValid = false;
} else {
$mobile_no = $_POST['mobile_no'];
}

// If all elds are valid, show success message


if ($isValid) {
5
ti
ti
fi
ti
ti
ti
tt
fi
tt
echo "<h3>All elds are valid. Registra on successful!</h3>";
}
}
?>

<!-- Form -->


<form method="POST">
<label>Name:</label>
<input type="text" name="name" value="<?php echo $name; ?>" required><br>
<span style="color:red"><?php echo $nameErr; ?></span><br><br>

<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>

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


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

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>";

// Using WHILE loop


echo "<h2>Numbers from 1 to 10 using WHILE loop</h2>";
$i = 1;
while ($i <= 10) {
echo $i . " ";
$i++;
}

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'];

// Display Customer Informa on


echo "<h3>Customer Informa on:</h3>";
echo "<b>Name:</b> " . htmlspecialchars($name) . "<br>";
echo "<b>Address:</b> " . nl2br(htmlspecialchars($address)) . "<br>";
echo "<b>Mobile Number:</b> " . htmlspecialchars($mobile_no) . "<br>";
echo "<b>Date of Birth:</b> " . htmlspecialchars($dob) . "<br>";
} else {
// Show the form if it's not yet submi ed
?>

<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>

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


</form>

<?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'];

echo "<h3>Factorial of $num using:</h3>";

// Using FOR loop


$factFor = 1;
for ($i = 1; $i <= $num; $i++) {
$factFor *= $i;
}
echo "FOR Loop: $factFor<br>";

// Using WHILE loop


$factWhile = 1;
$i = 1;
while ($i <= $num) {
$factWhile *= $i;
8
ti
ti
ti
ti
$i++;
}
echo "WHILE Loop: $factWhile<br>";

// Using DO...WHILE loop


$factDoWhile = 1;
$i = 1;
if ($num == 0) {
$factDoWhile = 1;
} else {
do {
$factDoWhile *= $i;
$i++;
} while ($i <= $num);
}
echo "DO...WHILE Loop: $factDoWhile<br>";
}
?>
</body>
</html>

2) Write a PHP programs to create database, create table and insert records in a table.

<?php
$servername = "localhost";
$username = "root";
$password = "";

// Step 1: Create connec on (without DB)


$conn = new mysqli($servername, $username, $password);

// Check connec on
if ($conn->connect_error) {
die("Connec on failed: " . $conn->connect_error);
}

// Step 2: Create Database


$sql = "CREATE DATABASE IF NOT EXISTS customerdb";
if ($conn->query($sql) === TRUE) {
echo "<b>Database 'customerdb' created successfully.</b><br>";
} else {
die("Error crea ng database: " . $conn->error);
}

// Step 3: Connect to the new database


$conn = new mysqli($servername, $username, $password, "customerdb");
if ($conn->connect_error) {
die("Connec on to database failed: " . $conn->connect_error);
}
9
ti
ti
ti
ti
ti
// Step 4: Create Table
$sql = "CREATE TABLE IF NOT EXISTS customers (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
address TEXT NOT NULL,
mobile_no VARCHAR(15),
dob DATE
)";

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


echo "<b>Table 'customers' created successfully.</b><br>";
} else {
die("Error crea ng table: " . $conn->error);
}

// Step 5: Insert Record


$sql = "INSERT INTO customers (name, address, mobile_no, dob)
VALUES ('John Doe', '123 Main Street', '9876543210', '1990-05-15')";

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


echo "<b>Sample record inserted successfully into 'customers'.</b><br>";
} else {
echo "Error inser ng record: " . $conn->error;
}

$conn->close();
?>

Ques on 6

1) Write a PHP program to nd largest of three numbers

<!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>

<label>Enter second number:</label>


<input type="number" name="num2" required><br><br>

<label>Enter third number:</label>


<input type="number" name="num3" required><br><br>
10
ti
ti
ti
fi
ti
fi
ti
<input type="submit" value="Find Largest">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$num3 = $_POST['num3'];

if ($num1 == $num2 && $num2 == $num3) {


echo "<b>All three numbers are equal: $num1</b>";
} else {
$largest = $num1;

if ($num2 > $largest) {


$largest = $num2;
}

if ($num3 > $largest) {


$largest = $num3;
}

echo "<b>The largest number is: $largest</b>";


}
}
?>
</body>
</html>

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";

// Step 1: Connect to MySQL and Create DB if not exists


$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) die("Connec on failed: " . $conn->connect_error);

$conn->query("CREATE DATABASE IF NOT EXISTS $dbname");


$conn->close();

// Step 2: Connect to the 'company' DB


$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) die("Connec on failed: " . $conn->connect_error);

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);

// Step 4: Insert form data into 'employee' table


if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$designa on = $_POST['designa on'];
$salary = $_POST['salary'];

$stmt = $conn->prepare("INSERT INTO employee (name, designa on, salary) VALUES (?, ?, ?)");
$stmt->bind_param("ssd", $name, $designa on, $salary);
$stmt->execute();

echo "<b>Record inserted successfully!</b><br><br>";


}
?>

<!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>

<input type="submit" value="Add Employee">


</form>

<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

1) Write a calendar program using switch statement.

<!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);
}

/* ======= UPDATE SECTION ======= */

$employee_id_update = 1; // ID of employee to update


$new_name = "Alice Smith";
$new_designa on = "Team Lead";
$new_salary = 55000.00;

$sql_update = "UPDATE employee SET name='$new_name', designa on='$new_designa on',


salary='$new_salary' WHERE id=$employee_id_update";
if ($conn->query($sql_update) === TRUE) {
echo "Employee with ID $employee_id_update updated successfully.\n";
} else {
echo "Error upda ng employee: " . $conn->error . "\n";
}

/* ======= DELETE SECTION ======= */

$employee_id_delete = 2; // ID of employee to delete

$sql_delete = "DELETE FROM employee WHERE id=$employee_id_delete";


if ($conn->query($sql_delete) === TRUE) {
echo "Employee with ID $employee_id_delete deleted successfully.\n";
} else {
echo "Error dele ng employee: " . $conn->error . "\n";
}

$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>";

$fruits = ["Apple", "Banana", "Mango", "Orange"];

// Using for loop


echo "Using for loop:<br>";
for ($i = 0; $i < count($fruits); $i++) {
echo "Fruit $i: " . $fruits[$i] . "<br>";
}

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>";

echo "<h2>2. Associa ve Array</h2>";

$student = [
"name" => "Amit",
"age" => 21,
"email" => "[email protected]"
];

// Using foreach loop


echo "Using foreach loop:<br>";
foreach ($student as $key => $value) {
echo uc rst($key) . ": $value<br>";
}

echo "<hr>";

echo "<h2>3. Mul dimensional Array</h2>";

$employees = [
["id" => 1, "name" => "John", "salary" => 40000],
["id" => 2, "name" => "Alice", "salary" => 45000],
["id" => 3, "name" => "Bob", "salary" => 42000]
];

// Using foreach loop


echo "Using foreach loop:<br>";
foreach ($employees as $employee) {
echo "ID: " . $employee["id"] . ", Name: " . $employee["name"] . ", Salary: " . $employee["salary"]
. "<br>";
}

// Using for loop


echo "<br>Using for loop:<br>";
for ($i = 0; $i < count($employees); $i++) {
echo "ID: " . $employees[$i]["id"] .
", Name: " . $employees[$i]["name"] .
", Salary: " . $employees[$i]["salary"] . "<br>";
}
?>

2) Write a PHP program for sending mail

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

if (mail($to, $subject, $message, $headers)) {


echo "Email sent successfully to $to.";
} else {
echo "Failed to send 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>";
}

echo "<h2>2. rsort() - Indexed array descending</h2>";


$numbers = [4, 1, 9, 2, 6];
rsort($numbers);
foreach ($numbers as $num) {
echo "$num<br>";
}

echo "<h2>3. asort() - Associa ve array sorted by value ascending</h2>";


$marks = ["Amit" => 85, "John" => 78, "Riya" => 92];
asort($marks);
foreach ($marks as $name => $mark) {
echo "$name : $mark<br>";
}

echo "<h2>4. arsort() - Associa ve array sorted by value descending</h2>";


arsort($marks);
foreach ($marks as $name => $mark) {
echo "$name : $mark<br>";
}

echo "<h2>5. ksort() - Associa ve array sorted by key ascending</h2>";


$person = ["c" => "Charlie", "a" => "Alice", "b" => "Bob"];
ksort($person);
foreach ($person as $key => $value) {
17
ti
ti
ti
ti
ti
ti
echo "$key : $value<br>";
}

echo "<h2>6. krsort() - Associa ve array sorted by key descending</h2>";


krsort($person);
foreach ($person as $key => $value) {
echo "$key : $value<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);
}

// Table name to count rows from


$table = "employee"; // Change to your table name

// Query to count total rows


$sql = "SELECT COUNT(*) AS total FROM $table";
$result = $conn->query($sql);

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";

// Display original string


echo "<b>Original String:</b> $str<br><br>";

// 1. str_word_count() - Count the number of words in the string


echo "<b>1. str_word_count():</b> " . str_word_count($str) . "<br>";

// 2. strlen() - Get the length of the string


echo "<b>2. strlen():</b> " . strlen($str) . "<br>";

// 3. strrev() - Reverse the string


echo "<b>3. strrev():</b> " . strrev($str) . "<br>";

// 4. strpos() - Find the posi on of a substring


echo "<b>4. strpos('PHP'):</b> " . strpos($str, "PHP") . "<br>";

// 5. str_replace() - Replace a word in the string


echo "<b>5. str_replace('PHP', 'Java'):</b> " . str_replace("PHP", "Java", $str) . "<br>";

// 6. ucwords() - Capitalize rst le er of each word


echo "<b>6. ucwords():</b> " . ucwords($str) . "<br>";

// 7. strtoupper() - Convert to uppercase


echo "<b>7. strtoupper():</b> " . strtoupper($str) . "<br>";

// 8. strtolower() - Convert to lowercase


echo "<b>8. strtolower():</b> " . strtolower($str) . "<br>";

// 9. empty() - Check if string is empty


$emptyStr = "";
echo "<b>9. empty():</b> ";
echo empty($emptyStr) ? "String is empty" : "String is not empty";
echo "<br>";
?>

2) Write a PHP programs to implements Single, Mul level and Mul ple inheritances.

<?php
echo "<h3>Single Inheritance</h3>";

// ======= Single Inheritance =======


class Animal {
public func on sound() {
echo "Animal makes a sound.<br>";
}
}

class Dog extends Animal {


public func on bark() {
19
ti
ti
fi
ti
tt
ti
ti
ti
echo "Dog barks.<br>";
}
}

$single = new Dog();


$single->sound();
$single->bark();

echo "<hr><h3>Mul level Inheritance</h3>";

// ======= Mul level Inheritance =======


class LivingBeing {
public func on breathe() {
echo "Living being breathes.<br>";
}
}

class Human extends LivingBeing {


public func on speak() {
echo "Human speaks.<br>";
}
}

class Student extends Human {


public func on study() {
echo "Student studies.<br>";
}
}

$mul Level = new Student();


$mul Level->breathe();
$mul Level->speak();
$mul Level->study();

echo "<hr><h3>Mul ple Inheritance (using Interfaces)</h3>";

// ======= Mul ple Inheritance via Interfaces =======


interface Writer {
public func on write();
}

interface Reader {
public func on read();
}

class Person implements Writer, Reader {


public func on write() {
echo "Person writes something.<br>";
}

20
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
public func on read() {
echo "Person reads something.<br>";

$mul = new Person();


$mul ->write();
$mul ->read();
?>

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;

for ($i = 0; $i < $length; $i++) {


$char = $input[$i];

// 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>";
?>

2) Develop a PHP programs to demonstrate func on overloading and overriding.

<?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>";
}
}
}
}

$obj = new OverloadExample();


$obj->greet("Alice"); // 1 argument
$obj->greet("Alice", "Bob"); // 2 arguments
$obj->greet(); // 0 arguments

echo "<hr><h2>Func on Overriding (Using Inheritance)</h2>";

// Base class
class Animal {
public func on makeSound() {
echo "Animal makes a sound.<br>";
}
}

// Derived class overrides method


class Dog extends Animal {
public func on makeSound() {
echo "Dog barks.<br>";
}
}

$animal = new Animal();


$animal->makeSound(); // Animal makes a sound

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 func on with parameters


func on greet($name, $ meOfDay) {
echo "Good $ meOfDay, $name!<br>";
}

// Calling with di erent arguments


greet("Alice", "Morning");
greet("Bob", "Evening");

echo "<hr><h2>2. Variable Func on</h2>";

// A named func on
func on sayHello() {
echo "Hello from variable func on!<br>";
}

// Assign func on name to a variable


$func = "sayHello";
$func(); // Call it like a func on

echo "<hr><h2>3. Anonymous Func on</h2>";

// Assigning an anonymous func on to a variable


$add = func on($a, $b) {
return $a + $b;
};

// Call the anonymous func on


$result = $add(10, 20);
echo "Result of anonymous add func on: $result<br>";
?>

2) Write PHP program for cloning of an object

<?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;
}

// Method to display info


public func on display() {
echo "Name: $this->name, Age: $this->age<br>";
}

// Magic method __clone (op onal, shows when object is cloned)


public func on __clone() {
echo "Cloning object...<br>";
}
}

// Create original object


$person1 = new Person("Alice", 25);
echo "Original Object:<br>";
$person1->display();

// Clone the object


$person2 = clone $person1;

// Modify cloned object


$person2->name = "Bob";
$person2->age = 30;

echo "<br>Cloned Object (a er modi ca on):<br>";


$person2->display();

echo "<br>Original Object (unchanged):<br>";


$person1->display();
?>

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');

// Create an image with a speci ed width and height


$image = imagecreatetruecolor(400, 300);

// Allocate colors for the image


$red = imagecolorallocate($image, 255, 0, 0); // Red color
24
ti
ti
ti
ti
ft
fi
ti
fi
ti
fi
$white = imagecolorallocate($image, 255, 255, 255); // White color for text

// Fill the background with white color


image ll($image, 0, 0, $white);

// Draw a lled red rectangle (x1, y1, x2, y2)


image lledrectangle($image, 50, 50, 350, 250, $red);

// Add text on the image (using white color)


$font = 5; // Built-in font size
$text = "Hello, World!";
imagestring($image, $font, 150, 130, $text, $white);

// Output the image to the browser


imagepng($image);

// Free up memory
imagedestroy($image);
?>

2) Write a PHP programs to demonstrate Serializa on and Introspec on

<?php

// ================== 1. Serializa on =======================


echo "<h2>Serializa on Example</h2>";

class Person {
public $name;
public $age;

// Constructor
public func on __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}

// Method to display informa on


public func on display() {
echo "Name: $this->name, Age: $this->age<br>";
}
}

// Create an object
$person = new Person("Alice", 30);

// Serialize the object into a string


$serializedPerson = serialize($person);
echo "Serialized Object: $serializedPerson<br>";

25
fi
fi
fi
ti
ti
ti
ti
ti
ti
ti
// Unserialize the object
$unserializedPerson = unserialize($serializedPerson);
echo "Unserialized Object: ";
$unserializedPerson->display();

echo "<hr>";

// ================== 2. Introspec on =======================

echo "<h2>Introspec on Example</h2>";

// Using Re ec onClass for introspec on


$className = "Person";
$re ec on = new Re ec onClass($className);

// Get class name


echo "Class Name: " . $re ec on->getName() . "<br>";

// Get class proper es


echo "Class Proper es: ";
$proper es = $re ec on->getProper es();
foreach ($proper es as $property) {
echo $property->getName() . " ";
}
echo "<br>";

// Get class methods


echo "Class Methods: ";
$methods = $re ec on->getMethods();
foreach ($methods as $method) {
echo $method->getName() . " ";
}
echo "<br>";

// Get constructor method


$constructor = $re ec on->getConstructor();
echo "Constructor: " . $constructor->getName() . "<br>";

?>

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

// De ne the Rectangle class


class Rectangle {
// Proper es for length and width
26
fl
fi
ti
ti
ti
fl
ti
ti
fl
ti
fl
fl
ti
ti
ti
fl
ti
ti
ti
ti
fl
ti
ti
ti
ti
ti
public $length;
public $width;

// Constructor to ini alize the proper es


public func on __construct($length, $width) {
$this->length = $length;
$this->width = $width;
}

// Method to calculate the area of the rectangle


public func on calculateArea() {
return $this->length * $this->width;
}

// Method to calculate the perimeter of the rectangle


public func on calculatePerimeter() {
return 2 * ($this->length + $this->width);
}
}

// Crea ng two objects of the Rectangle class

// First object with length 5 and width 3


$rectangle1 = new Rectangle(5, 3);

// Second object with length 7 and width 4


$rectangle2 = new Rectangle(7, 4);

// Display area and perimeter for the rst rectangle


echo "Rectangle 1 - Length: $rectangle1->length, Width: $rectangle1->width<br>";
echo "Area: " . $rectangle1->calculateArea() . "<br>";
echo "Perimeter: " . $rectangle1->calculatePerimeter() . "<br><br>";

// Display area and perimeter for the second rectangle


echo "Rectangle 2 - Length: $rectangle2->length, Width: $rectangle2->width<br>";
echo "Area: " . $rectangle2->calculateArea() . "<br>";
echo "Perimeter: " . $rectangle2->calculatePerimeter() . "<br>";

?>

2) Write a PHP program to create access, modify and delete a cookie.

<?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
}

// ================== 2. Access a Cookie =====================


echo "<h3>Accessing Cookie:</h3>";
if (isset($_COOKIE['user'])) {
echo "Hello, " . $_COOKIE['user'] . "!<br>";
} else {
echo "Cookie 'user' is not set!<br>";
}

// ================== 3. Modify the Cookie ====================


echo "<h3>Modifying Cookie:</h3>";
// Modify the cookie by se ng it again with a new value
if (isset($_COOKIE['user'])) {
setcookie("user", "JaneDoe", me() + 3600, "/"); // Update cookie value to 'JaneDoe'
echo "Cookie 'user' is modi ed to: " . $_COOKIE['user'] . "<br>";
} else {
echo "Cookie 'user' is not set, so cannot be modi ed.<br>";
}

// ================== 4. Delete a Cookie =====================


// To delete a cookie, we set the expiry me to the past
echo "<h3>Dele ng Cookie:</h3>";
if (isset($_COOKIE['user'])) {
setcookie("user", "", me() - 3600, "/"); // Set expiry me to the past
echo "Cookie 'user' has been deleted.<br>";
} else {
echo "Cookie 'user' was not set, so it cannot be deleted.<br>";
}

?>

Ques on 15

1) Write a PHP programs to demonstrate default constructor, parameterized constructor and


destructor

<?php

// ================== Default Constructor =====================


class Person {
public $name;
public $age;

// Default Constructor (no parameters)


public func on __construct() {
$this->name = "Unknown";
$this->age = 0;
echo "Default Constructor called: Person created with default values.<br>";
}
28
ti
ti
ti
ti
tti
fi
ti
ti
fi
ti
// Destructor
public func on __destruct() {
echo "Destructor called: Object of Person destroyed.<br>";
}

// Method to display the person's details


public func on display() {
echo "Name: $this->name, Age: $this->age<br>";
}
}

// ================== Parameterized Constructor =====================


class Student {
public $name;
public $age;
public $course;

// 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>";
}

// Method to display the student's details


public func on display() {
echo "Name: $this->name, Age: $this->age, Course: $this->course<br>";
}
}

// ================== Tes ng Default Constructor =====================


echo "<h3>Using Default Constructor:</h3>";
$person = new Person(); // Default constructor is called
$person->display(); // Display default values
unset($person); // Object is destroyed, and destructor is called
echo "<hr>";
// ================== Tes ng Parameterized Constructor =====================
echo "<h3>Using Parameterized Constructor:</h3>";
$student = new Student("John", 22, "Computer Science"); // Parameterized constructor is called
$student->display(); // Display student's details
unset($student); // Object is destroyed, and destructor is called

?>
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

// ========================= 2. Set Session Variables ========================


if (!isset($_SESSION['username'])) {
$_SESSION['username'] = "JohnDoe"; // Se ng session variable for username
$_SESSION['email'] = "[email protected]"; // Se ng session variable for email
echo "Session variables 'username' and 'email' are set. <br>";
} else {
echo "Session variables are already set.<br>";
}
// ========================= 3. Get Session Variables ========================
echo "<h3>Ge ng Session Variables:</h3>";
if (isset($_SESSION['username']) && isset($_SESSION['email'])) {
echo "Username: " . $_SESSION['username'] . "<br>";
echo "Email: " . $_SESSION['email'] . "<br>";
} else {
echo "Session variables are not set!<br>";
}
// ========================= 4. Modify Session Variables ========================
echo "<h3>Modifying Session Variables:</h3>";
if (isset($_SESSION['username']) && isset($_SESSION['email'])) {
$_SESSION['username'] = "JaneDoe"; // Modifying session variable
$_SESSION['email'] = "[email protected]"; // Modifying session variable
echo "Session variables have been modi ed.<br>";
} else {
echo "Session variables are not set, so cannot be modi ed.<br>";
}
// Display modi ed session variables
echo "Modi ed Username: " . $_SESSION['username'] . "<br>";
echo "Modi ed Email: " . $_SESSION['email'] . "<br>";
// ========================= 5. Destroy Session =========================
echo "<h3>Destroying Session:</h3>";
session_unset(); // Unset all session variables
session_destroy(); // Destroy the session

// Check if session variables are s ll available a er destroying session


if (isset($_SESSION['username']) || isset($_SESSION['email'])) {
echo "Session is s ll ac ve.<br>";
} else {
echo "Session is destroyed, and variables are cleared.<br>";
}
?>

30
fi
fi
tti
fi
ti
ti
ti
fi
tti
ft
fi
tti

You might also like