0% found this document useful (0 votes)
3 views14 pages

PHP Lab Manual

The PHP Lab Manual provides a series of experiments designed for undergraduate students in the Department of Computer Science, covering fundamental PHP programming concepts. Each experiment includes objectives, theory, PHP code examples, and expected outputs, ranging from basic 'Hello World' scripts to more complex tasks involving MySQL database interactions. The manual serves as a practical guide for students to learn and apply PHP programming skills through hands-on exercises.

Uploaded by

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

PHP Lab Manual

The PHP Lab Manual provides a series of experiments designed for undergraduate students in the Department of Computer Science, covering fundamental PHP programming concepts. Each experiment includes objectives, theory, PHP code examples, and expected outputs, ranging from basic 'Hello World' scripts to more complex tasks involving MySQL database interactions. The manual serves as a practical guide for students to learn and apply PHP programming skills through hands-on exercises.

Uploaded by

shayarigazak
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PHP Lab Manual | Department of Computer Science

PHP PROGRAMMING
Laboratory Manual

Prepared for Undergraduate Students


Department of Computer Science & Applications

Student Details
Name : ___________________________________
Roll Number : ___________________________________
Semester : ___________________________________
Batch : ___________________________________

Page 1
PHP Lab Manual | Department of Computer Science

TABLE OF CONTENTS

Experiment 01 Hello World in PHP


Experiment 02 Maximum of Three Numbers & Switch Statement
Experiment 03 Factorial Using While Loop
Experiment 04 Count Positive, Negative & Zeros (Do-While Loop)
Experiment 05 Array Transformation (Even/Odd Operations)
Experiment 06 Associative Array – Countries & Cities Table
Experiment 07 Function to Calculate Average Marks
Experiment 08 Factorial Using Recursion
Experiment 09 Time-Based Greeting Message
Experiment 10 Student Mark List Processing with MySQL

Page 2
PHP Lab Manual | Department of Computer Science

EXPERIMENT 01 | Hello World in PHP

AIM To create a PHP webpage and print 'Hello World'.

PHP (Hypertext Preprocessor) is a widely-used server-side scripting language


embedded in HTML. PHP code is executed on the server, and the output is returned to
THEORY
the browser as plain HTML. Every PHP file starts with <?php and ends with ?>. The
echo statement is used to output text.

PHP CODE
<?php
echo "Hello World!";
?>

OUTPUT
Hello World!

NOTE: Save this file as [Link] in your server's root directory (htdocs for XAMPP). Open your browser and go to
[Link] to see the output.

Page 3
PHP Lab Manual | Department of Computer Science

EXPERIMENT 02 | Maximum of Three Numbers & Switch Statement

To write PHP programs to (a) find the maximum of three numbers and (b) use a switch
AIM
statement.

PHP provides if-elseif-else constructs for conditional logic and a switch statement for
multiple-case branching. The switch statement evaluates a variable and executes the
THEORY
matching case block, making code cleaner when comparing one variable to many
values.

PHP CODE
<?php
// Part A: Maximum of three numbers
$a = 45;
$b = 78;
$c = 31;

if ($a >= $b && $a >= $c) {


echo "Maximum is: $a";
} elseif ($b >= $a && $b >= $c) {
echo "Maximum is: $b";
} else {
echo "Maximum is: $c";
}

// Part B: Switch Statement


$var = "1";

switch ($var) {
case "1":
echo "\nHello";
break;
case "2":
echo "\nWelcome";
break;
default:
echo "\nInvalid input";
}
?>

OUTPUT
Maximum is: 78
Hello

NOTE: Change the values of $a, $b, $c and $var to test different scenarios.

Page 4
PHP Lab Manual | Department of Computer Science

EXPERIMENT 03 | Factorial Using While Loop

AIM To compute the factorial of a number using a While loop in PHP.

Factorial of a non-negative integer n (written as n!) is the product of all positive integers
THEORY less than or equal to n. For example, 5! = 5x4x3x2x1 = 120. A while loop repeats a
block of code as long as a specified condition is true.

PHP CODE
<?php
$num = 6;
$factorial = 1;
$i = 1;

while ($i <= $num) {


$factorial = $factorial * $i;
$i++;
}

echo "Factorial of $num is: $factorial";


?>

OUTPUT
Factorial of 6 is: 720

NOTE: Try changing $num to 0 or 1 to see edge cases. Factorial of 0 is 1 by convention.

Page 5
PHP Lab Manual | Department of Computer Science

EXPERIMENT 04 | Count Positive, Negative & Zeros (Do-While Loop)

To enter numbers until the user wants to stop and display the count of positive,
AIM
negative and zero values using a do-while loop.

A do-while loop executes the code block at least once before checking the condition,
THEORY making it useful for input validation. Here we simulate user input using an array to
demonstrate the logic.

PHP CODE
<?php
// Simulating user input with an array
$numbers = [5, -3, 0, 8, -1, 0, 12, -7, 0, 4];
$index = 0;
$positive = 0;
$negative = 0;
$zeros = 0;
$total = count($numbers);

do {
$num = $numbers[$index];
echo "Entered: $num\n";

if ($num > 0) {
$positive++;
} elseif ($num < 0) {
$negative++;
} else {
$zeros++;
}
$index++;
} while ($index < $total);

echo "\n--- Summary ---\n";


echo "Positive Numbers: $positive\n";
echo "Negative Numbers: $negative\n";
echo "Zeros: $zeros\n";
?>

OUTPUT
Entered: 5
Entered: -3
Entered: 0
Entered: 8
Entered: -1
Entered: 0
Entered: 12
Entered: -7
Entered: 0
Entered: 4

--- Summary ---


Positive Numbers: 4

Page 6
PHP Lab Manual | Department of Computer Science

Negative Numbers: 3
Zeros: 3

NOTE: In a real web form, you would use $_POST or $_GET to collect actual user input.

Page 7
PHP Lab Manual | Department of Computer Science

EXPERIMENT 05 | Array Transformation (Even/Odd Operations)

To accept an array of integers and output a new array: even numbers divided by 2, odd
AIM
numbers multiplied by 3.

PHP arrays are flexible data structures. The modulus operator (%) returns the
THEORY remainder of division. If $n % 2 == 0, the number is even; otherwise it's odd. We iterate
through the array using foreach loop and apply the required transformation.

PHP CODE
<?php
$input = [4, 7, 10, 3, 16, 9, 2, 5];
$output = [];

foreach ($input as $num) {


if ($num % 2 == 0) {
$output[] = $num / 2; // Even: divide by 2
} else {
$output[] = $num * 3; // Odd: multiply by 3
}
}

echo "Input Array: ";


echo implode(", ", $input);
echo "\nOutput Array: ";
echo implode(", ", $output);
?>

OUTPUT
Input Array: 4, 7, 10, 3, 16, 9, 2, 5
Output Array: 2, 21, 5, 9, 8, 27, 1, 15

NOTE: implode() joins array elements into a string with the given separator.

Page 8
PHP Lab Manual | Department of Computer Science

EXPERIMENT 06 | Associative Array – Countries & Cities Table

To create an associative array using countries as keys and cities as values, and
AIM
display it as an HTML table.

An associative array uses named keys instead of numeric indices. In PHP, associative
THEORY arrays are declared using => notation. HTML tables are created with <table>, <tr>
(table row), <th> (table header), and <td> (table data) tags.

PHP CODE
<?php
$countries = [
"India" => "New Delhi",
"United States" => "Washington D.C.",
"France" => "Paris",
"Japan" => "Tokyo",
"Australia" => "Canberra",
"Germany" => "Berlin",
];

echo "<table border='1' cellpadding='10'>";


echo "<tr><th>Country</th><th>Capital City</th></tr>";

foreach ($countries as $country => $city) {


echo "<tr>";
echo "<td>$country</td>";
echo "<td>$city</td>";
echo "</tr>";
}

echo "</table>";
?>

OUTPUT
+----------------+------------------+
| Country | Capital City |
+----------------+------------------+
| India | New Delhi |
| United States | Washington D.C. |
| France | Paris |
| Japan | Tokyo |
| Australia | Canberra |
| Germany | Berlin |
+----------------+------------------+

NOTE: In the browser, this renders as a proper HTML table with borders and padding.

Page 9
PHP Lab Manual | Department of Computer Science

EXPERIMENT 07 | Function to Calculate Average Marks

To write a PHP function calculate_Average() that takes four course marks as


AIM
arguments and returns their average.

Functions in PHP are defined using the function keyword. They can accept parameters
THEORY (arguments) and return values using return. Functions help avoid code repetition and
make code modular and reusable.

PHP CODE
<?php
function calculate_Average($m1, $m2, $m3, $m4) {
$sum = $m1 + $m2 + $m3 + $m4;
$average = $sum / 4;
return $average;
}

// Test with sample marks


$course1 = 85;
$course2 = 90;
$course3 = 78;
$course4 = 92;

$avg = calculate_Average($course1, $course2, $course3, $course4);

echo "Marks Entered:\n";


echo " Course 1: $course1\n";
echo " Course 2: $course2\n";
echo " Course 3: $course3\n";
echo " Course 4: $course4\n";
echo "Average Marks: $avg";
?>

OUTPUT
Marks Entered:
Course 1: 85
Course 2: 90
Course 3: 78
Course 4: 92
Average Marks: 86.25

NOTE: You can extend this function to accept variable arguments using ...$marks syntax for more flexibility.

Page 10
PHP Lab Manual | Department of Computer Science

EXPERIMENT 08 | Factorial Using Recursion

AIM To compute the factorial of a number using recursion in PHP.

Recursion is a technique where a function calls itself to solve a smaller version of the
same problem. Every recursive function must have: (1) a base case to stop the
THEORY
recursion, and (2) a recursive case that moves toward the base case. For factorial:
factorial(n) = n * factorial(n-1), and factorial(0) = 1 (base case).

PHP CODE
<?php
function factorial($n) {
// Base case: factorial of 0 or 1 is 1
if ($n == 0 || $n == 1) {
return 1;
}
// Recursive case
return $n * factorial($n - 1);
}

$number = 7;
$result = factorial($number);
echo "Factorial of $number = $result";

// Show how recursion works step by step


echo "\n\nHow it works:";
echo "\n7! = 7 x 6 x 5 x 4 x 3 x 2 x 1 = 5040";
?>

OUTPUT
Factorial of 7 = 5040

How it works:
7! = 7 x 6 x 5 x 4 x 3 x 2 x 1 = 5040

NOTE: Recursion is elegant but uses more memory than loops. For very large numbers, loops are more efficient.

Page 11
PHP Lab Manual | Department of Computer Science

EXPERIMENT 09 | Time-Based Greeting Message

To display a greeting message based on the time of day (Good Morning / Good
AIM
Afternoon / Good Evening).

PHP's date() function returns the current date/time formatted according to a format
THEORY string. The 'H' format returns the hour in 24-hour format (00-23). We compare the
current hour to display an appropriate greeting.

PHP CODE
<?php
$hour = (int) date('H'); // Get current hour (0-23)

echo "Current Hour: $hour:00\n\n";

if ($hour >= 5 && $hour < 12) {


$greeting = "Good Morning! Rise and shine!";
} elseif ($hour >= 12 && $hour < 17) {
$greeting = "Good Afternoon! Hope your day is going well!";
} elseif ($hour >= 17 && $hour < 21) {
$greeting = "Good Evening! Time to relax!";
} else {
$greeting = "Good Night! Sweet dreams!";
}

echo $greeting;
?>

OUTPUT
Current Hour: 9:00

Good Morning! Rise and shine!

NOTE: The output will change depending on when you run the script. PHP uses the server's timezone by default.

Page 12
PHP Lab Manual | Department of Computer Science

EXPERIMENT 10 | Student Mark List Processing with MySQL

To create a Student Mark List system by executing DDL, DML, and DCL commands on
AIM
a MySQL database using PHP.

Database commands are categorized as: DDL (Data Definition Language) - CREATE,
DROP, ALTER; DML (Data Manipulation Language) - INSERT, SELECT, UPDATE,
THEORY
DELETE; DCL (Data Control Language) - GRANT, REVOKE. PHP connects to MySQL
using MySQLi or PDO extensions.

PHP CODE
<?php
// Database Connection
$conn = mysqli_connect("localhost", "root", "", "school_db");

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// ===== DDL: Create Table =====


$sql = "CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
english INT,
maths INT,
science INT,
total INT,
grade VARCHAR(5)
)";
mysqli_query($conn, $sql);
echo "Table created successfully!\n";

// ===== DML: Insert Records =====


$sql = "INSERT INTO students (name, english, maths, science, total, grade) VALUES
('Alice', 85, 92, 88, 265, 'A'),
('Bob', 70, 65, 78, 213, 'B'),
('Charlie',55, 60, 50, 165, 'C')";
mysqli_query($conn, $sql);
echo "Records inserted!\n\n";

// ===== DML: Select & Display =====


$result = mysqli_query($conn, "SELECT * FROM students");
echo "Name | English | Maths | Science | Total | Grade\n";
echo str_repeat("-", 55) . "\n";

while ($row = mysqli_fetch_assoc($result)) {


echo "{$row['name']}\t| {$row['english']}\t | {$row['maths']}\t |
{$row['science']}\t | {$row['total']}\t | {$row['grade']}\n";
}

// ===== DML: Update =====


$sql = "UPDATE students SET grade='A+' WHERE total > 260";
mysqli_query($conn, $sql);

Page 13
PHP Lab Manual | Department of Computer Science

echo "\nGrades updated!\n";

// ===== DCL: Grant Privileges =====


// Run in MySQL as admin:
// GRANT SELECT ON school_db.students TO 'viewer'@'localhost';

mysqli_close($conn);
?>

OUTPUT
Table created successfully!
Records inserted!

Name | English | Maths | Science | Total | Grade


-------------------------------------------------------
Alice | 85 | 92 | 88 | 265 | A
Bob | 70 | 65 | 78 | 213 | B
Charlie | 55 | 60 | 50 | 165 | C

Grades updated!

NOTE: Make sure XAMPP/WAMP is running with MySQL. Create the database 'school_db' first using phpMyAdmin or the
MySQL command line.

Page 14

You might also like