PHP PROGRAMS
1. Write a PHP program to Display “Hello”, and today’s date.
<?php
// Display greeting
echo "Hello<br>";
// Display today's date in YYYY-MM-DD format
echo "Today's date is: " . date("Y-m-d");
?>
*****
2. Write a PHP program to display Fibonacci series.
<?php
// Number of terms in the Fibonacci series
$terms = 10;
// Initialize first two Fibonacci numbers
$first = 0;
$second = 1;
echo "Fibonacci series for $terms terms:<br>";
// Print the first two terms
echo $first . ", " . $second;
// Generate the rest of the series
for ($i = 3; $i <= $terms; $i++) {
$next = $first + $second;
echo ", " . $next;
// Update variables for next iteration
$first = $second;
$second = $next;
}
?>
*****
3. Write a PHP Program to read the employee details.
<!DOCTYPE html>
<html>
<head>
<title>Employee Details</title>
</head>
<body>
<h2>Enter Employee Details</h2>
<form method="post" action="">
<label for="emp_id">Employee ID:</label><br>
<input type="text" name="emp_id" required><br><br>
<label for="emp_name">Employee Name:</label><br>
<input type="text" name="emp_name" required><br><br>
<label for="department">Department:</label><br>
<input type="text" name="department" required><br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
// Check if form is submitted
if (isset($_POST['submit'])) {
// Read form data
$emp_id = $_POST['emp_id'];
$emp_name = $_POST['emp_name'];
$department = $_POST['department'];
// Display the employee details
echo "<h3>Employee Details Submitted:</h3>";
echo "Employee ID: " . htmlspecialchars($emp_id) . "<br>";
echo "Employee Name: " . htmlspecialchars($emp_name) . "<br>";
echo "Department: " . htmlspecialchars($department);
}
?>
</body>
</html>
*****
4. Write a PHP program to prepare the student marks list.
<!DOCTYPE html>
<html>
<head>
<title>Student Marks List</title>
</head>
<body>
<h2>Enter Student Details and Marks</h2>
<form method="post" action="">
<label for="roll">Roll Number:</label><br>
<input type="text" name="roll" required><br><br>
<label for="name">Student Name:</label><br>
<input type="text" name="name" required><br><br>
<label for="subject1">Marks in Subject 1:</label><br>
<input type="number" name="subject1" min="0" max="100" required><br><br>
<label for="subject2">Marks in Subject 2:</label><br>
<input type="number" name="subject2" min="0" max="100" required><br><br>
<label for="subject3">Marks in Subject 3:</label><br>
<input type="number" name="subject3" min="0" max="100" required><br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
// Check if form is submitted
if (isset($_POST['submit'])) {
// Collect input data
$roll = $_POST['roll'];
$name = $_POST['name'];
$subject1 = (int) $_POST['subject1'];
$subject2 = (int) $_POST['subject2'];
$subject3 = (int) $_POST['subject3'];
// Calculate total and average
$total = $subject1 + $subject2 + $subject3;
$average = $total / 3;
// Display the marks list
echo "<h3>Student Marks List</h3>";
echo "Roll Number: " . htmlspecialchars($roll) . "<br>";
echo "Student Name: " . htmlspecialchars($name) . "<br>";
echo "Subject 1: $subject1<br>";
echo "Subject 2: $subject2<br>";
echo "Subject 3: $subject3<br>";
echo "Total Marks: $total<br>";
echo "Average Marks: " . number_format($average, 2);
}
?>
</body>
</html>
*****
5. Write a PHP program to generate the multiplication of two matrices.
<?php
// Define the first matrix (2x3)
$matrix1 = [
[1, 2, 3],
[4, 5, 6]
];
// Define the second matrix (3x2)
$matrix2 = [
[7, 8],
[9, 10],
[11, 12]
];
// Get dimensions
$rows1 = count($matrix1); // 2
$cols1 = count($matrix1[0]); // 3
$rows2 = count($matrix2); // 3
$cols2 = count($matrix2[0]); // 2
// Check if multiplication is possible (cols1 == rows2)
if ($cols1 != $rows2) {
echo "Matrix multiplication is not possible.";
exit;
}
// Initialize result matrix with zeros
$result = [];
for ($i = 0; $i < $rows1; $i++) {
for ($j = 0; $j < $cols2; $j++) {
$result[$i][$j] = 0;
for ($k = 0; $k < $cols1; $k++) {
$result[$i][$j] += $matrix1[$i][$k] * $matrix2[$k][$j];
}
}
}
// Display the result
echo "<h3>Matrix Multiplication Result:</h3>";
for ($i = 0; $i < $rows1; $i++) {
for ($j = 0; $j < $cols2; $j++) {
echo $result[$i][$j] . " ";
}
echo "<br>";
}
?>
*****
6. Create student registration form using text box, check box, radio button,
select, submit button. And display user inserted value in new PHP page.
HTML Program:
<!DOCTYPE html>
<html>
<head>
<title>Student Registration Form</title>
</head>
<body>
<h2>Student Registration Form</h2>
<form method="post" action="display_student.php">
<label for="name">Full Name:</label><br>
<input type="text" name="name" required><br><br>
<label for="email">Email:</label><br>
<input type="email" name="email" required><br><br>
<label>Gender:</label><br>
<input type="radio" name="gender" value="Male" required> Male
<input type="radio" name="gender" value="Female"> Female<br><br>
<label>Hobbies:</label><br>
<input type="checkbox" name="hobbies[]" value="Reading"> Reading
<input type="checkbox" name="hobbies[]" value="Sports"> Sports
<input type="checkbox" name="hobbies[]" value="Music"> Music<br><br>
<label for="course">Course:</label><br>
<select name="course" required>
<option value="">--Select--</option>
<option value="Computer Science">Computer Science</option>
<option value="Computer Applications">Computer Applications</option>
<option value="Commerce">Commerce</option>
</select><br><br>
<input type="submit" value="Register">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST["name"]);
$email = htmlspecialchars($_POST["email"]);
$gender = htmlspecialchars($_POST["gender"]);
$course = htmlspecialchars($_POST["course"]);
$hobbies = isset($_POST["hobbies"]) ? $_POST["hobbies"] : [];
echo "<h2>Student Registration Details</h2>";
echo "Name: $name<br>";
echo "Email: $email<br>";
echo "Gender: $gender<br>";
echo "Course: $course<br>";
echo "Hobbies: ";
if (count($hobbies) > 0) {
echo implode(", ", array_map('htmlspecialchars', $hobbies));
} else {
echo "None";
}
}
?>
</body>
</html>
*****
7. Create Website Registration Form using text box, check box, radio button,
select, submit button. And display user inserted value in new PHP page.
<!DOCTYPE html>
<html>
<head>
<title>Website Registration Form</title>
</head>
<body>
<h2>Website Registration</h2>
<form method="post" action="registration_result.php">
<label for="username">Username:</label><br>
<input type="text" name="username" required><br><br>
<label for="email">Email:</label><br>
<input type="email" name="email" required><br><br>
<label for="password">Password:</label><br>
<input type="password" name="password" required><br><br>
<label>Gender:</label><br>
<input type="radio" name="gender" value="Male" required> Male
<input type="radio" name="gender" value="Female"> Female
<input type="radio" name="gender" value="Other"> Other<br><br>
<label>Interests:</label><br>
<input type="checkbox" name="interests[]" value="Technology"> Technology
<input type="checkbox" name="interests[]" value="Sports"> Sports
<input type="checkbox" name="interests[]" value="Music"> Music
<input type="checkbox" name="interests[]" value="Travel"> Travel<br><br>
<label for="country">Country:</label><br>
<select name="country" required>
<option value="">--Select Country--</option>
<option value="USA">USA</option>
<option value="India">India</option>
<option value="UK">UK</option>
<option value="Canada">Canada</option>
</select><br><br>
<input type="submit" value="Register">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Collect data with validation
$username = htmlspecialchars($_POST["username"]);
$email = htmlspecialchars($_POST["email"]);
$password = htmlspecialchars($_POST["password"]); // Never display in real apps
$gender = htmlspecialchars($_POST["gender"]);
$country = htmlspecialchars($_POST["country"]);
$interests = isset($_POST["interests"]) ? $_POST["interests"] : [];
echo "<h2>Registration Details</h2>";
echo "Username: $username<br>";
echo "Email: $email<br>";
echo "Gender: $gender<br>";
echo "Country: $country<br>";
echo "Interests: ";
if (!empty($interests)) {
echo implode(", ", array_map('htmlspecialchars', $interests));
} else {
echo "None";
}
}
?>
</body>
</html>
*****
8. Write PHP script to demonstrate passing variables with cookies.
<?php
// Set a cookie named "username" with value "Anitha"
setcookie("username", "Anitha", time() + (86400 * 1), "/"); // 1 day expiry
echo "Cookie has been set. <a href='get_cookie.php'>Click here to read the
cookie</a>";
if (isset($_COOKIE["username"])) {
$user = htmlspecialchars($_COOKIE["username"]);
echo "Welcome back, $user!";
} else {
echo "Cookie is not set.";
}
?>
*****
9. Write a program to keep track of how many times a visitor has loaded the page.
<?php
// Check if the 'visit_count' cookie exists
if (isset($_COOKIE['visit_count'])) {
// Increment the visit count
$visit_count = $_COOKIE['visit_count'] + 1;
} else {
// First visit
$visit_count = 1;
}
// Set or update the cookie (expires in 1 day)
setcookie("visit_count", $visit_count, time() + (86400 * 1)); // 86400 = 1 day in seconds
?>
<!DOCTYPE html>
<html>
<head>
<title>Visit Counter</title>
</head>
<body>
<h2>Welcome to the Page</h2>
<p>
<?php
echo "You have visited this page <strong>$visit_count</strong> times.";
?>
</p>
</body>
</html>
*****
[Link] a PHP application to add new Rows in a Table.
<?php
session_start();
// Initialize table data if not already set
if (!isset($_SESSION['table_data'])) {
$_SESSION['table_data'] = [];
}
// If form is submitted, add new row to session data
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
// Append the new row to the session
$_SESSION['table_data'][] = ['name' => $name, 'email' => $email];
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Add Rows to Table</title>
</head>
<body>
<h2>Add New Row</h2>
<form method="post" action="">
<label>Name:</label><br>
<input type="text" name="name" required><br><br>
<label>Email:</label><br>
<input type="email" name="email" required><br><br>
<input type="submit" value="Add Row">
</form>
<h2>Table Data</h2>
<table border="1" cellpadding="10">
<tr>
<th>Name</th>
<th>Email</th>
</tr>
<?php foreach ($_SESSION['table_data'] as $row): ?>
<tr>
<td><?= $row['name']; ?></td>
<td><?= $row['email']; ?></td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>
*****
[Link] a PHP application to modify the Rows in a Table.
<?php
session_start();
// Initialize data
if (!isset($_SESSION['table_data'])) {
$_SESSION['table_data'] = [
['name' => 'Alice', 'email' => 'alice@[Link]'],
['name' => 'Bob', 'email' => 'bob@[Link]'],
];
}
// Handle update request
if (isset($_POST['update'])) {
$index = $_POST['index'];
$_SESSION['table_data'][$index]['name'] = htmlspecialchars($_POST['name']);
$_SESSION['table_data'][$index]['email'] = htmlspecialchars($_POST['email']);
header("Location: modify_table.php");
exit;
}
// Handle edit request
$editIndex = isset($_GET['edit']) ? (int)$_GET['edit'] : -1;
?>
<!DOCTYPE html>
<html>
<head>
<title>Modify Table Rows</title>
</head>
<body>
<h2>Modify Rows in Table</h2>
<table border="1" cellpadding="10">
<tr>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
<?php foreach ($_SESSION['table_data'] as $index => $row): ?>
<tr>
<?php if ($index === $editIndex): ?>
<!-- Editable row -->
<form method="post" action="">
<td>
<input type="text" name="name" value="<?=
htmlspecialchars($row['name']) ?>" required>
</td>
<td>
<input type="email" name="email" value="<?=
htmlspecialchars($row['email']) ?>" required>
</td>
<td>
<input type="hidden" name="index" value="<?= $index ?>">
<input type="submit" name="update" value="Update">
<a href="modify_table.php">Cancel</a>
</td>
</form>
<?php else: ?>
<!-- Static row -->
<td><?= htmlspecialchars($row['name']) ?></td>
<td><?= htmlspecialchars($row['email']) ?></td>
<td><a href="?edit=<?= $index ?>">Edit</a></td>
<?php endif; ?>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>
*****
[Link] a PHP application to delete the Rows from a Table.
<?php
session_start();
// Initialize with sample data if not already set
if (!isset($_SESSION['table_data'])) {
$_SESSION['table_data'] = [
['name' => 'Alice', 'email' => 'alice@[Link]'],
['name' => 'Bob', 'email' => 'bob@[Link]'],
['name' => 'Charlie', 'email' => 'charlie@[Link]'],
];
}
// Handle delete request
if (isset($_GET['delete'])) {
$index = (int) $_GET['delete'];
if (isset($_SESSION['table_data'][$index])) {
unset($_SESSION['table_data'][$index]);
// Re-index the array to avoid gaps
$_SESSION['table_data'] = array_values($_SESSION['table_data']);
}
// Redirect to avoid re-executing deletion on refresh
header("Location: delete_row_table.php");
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Delete Rows from Table</title>
</head>
<body>
<h2>Delete Rows from Table</h2>
<table border="1" cellpadding="10">
<tr>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
<?php if (!empty($_SESSION['table_data'])): ?>
<?php foreach ($_SESSION['table_data'] as $index => $row): ?>
<tr>
<td><?= htmlspecialchars($row['name']) ?></td>
<td><?= htmlspecialchars($row['email']) ?></td>
<td><a href="?delete=<?= $index ?>" onclick="return confirm('Are you
sure you want to delete this row?');">Delete</a></td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="3">No data available.</td>
</tr>
<?php endif; ?>
</table>
</body>
</html>
*****
[Link] a PHP application to fetch the Rows in a Table.
<?php
// Database connection parameters
$host = "localhost";
$user = "root";
$password = ""; // Default for XAMPP/WAMP
$database = "your_database_name";
// Create connection
$conn = new mysqli($host, $user, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch all rows from the 'students' table
$sql = "SELECT * FROM students";
$result = $conn->query($sql);
?>
<!DOCTYPE html>
<html>
<head>
<title>Fetch Students</title>
</head>
<body>
<h2>Student List</h2>
<table border="1" cellpadding="10">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
<?php if ($result && $result->num_rows > 0): ?>
<?php while ($row = $result->fetch_assoc()): ?>
<tr>
<td><?= htmlspecialchars($row['id']) ?></td>
<td><?= htmlspecialchars($row['name']) ?></td>
<td><?= htmlspecialchars($row['email']) ?></td>
</tr>
<?php endwhile; ?>
<?php else: ?>
<tr>
<td colspan="3">No records found.</td>
</tr>
<?php endif; ?>
</table>
</body>
</html>
<?php
// Close connection
$conn->close();
?>
*****