1.
write a program to compute the sum of digits of a
number.(Input get using Form)
<!DOCTYPE html>
<html>
<head>
<title>Sum of Digits </title>
</head>
<body>
<h2>Sum of Digits of Number</h2>
<form method="post" action="<?php echohtmlspecialchars($_SERVER["PHP_SELF"]);>">
Enter a number:
<input type="text" name="number">
<input type="submit" value="Calculate">
</form>
<?php
function sumOfDigits($number) {
$sum = 0;
while ($number != 0) {
$digit = $number % 10; // Get the last digit
$sum += $digit; // Add digit to sum
$number = (int)($number / 10);
return $sum;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$number = $_POST["number"];
if (is_numeric($number) && $number >= 0 && is_int((int)$number)) {
$result = sumOfDigits($number);
echo "<p>Sum of digits of $number is: $result</p>";
} else {
echo "<p>Please enter a valid non-negative integer.</p>";
}
}
?>
</body>
</html>
2. Write a program to inserts a new item in an array in any array
position.(Input get using form)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert Item in Array</title>
</head>
<body>
<h2>Insert Item into Array</h2>
<form action="" method="post">
<label for="array">Enter array (comma-separated):</label><br>
<input type="text" id="array" name="array" required><br><br>
<label for="item">Item to insert:</label><br>
<input type="text" id="item" name="item" required><br><br>
<label for="position">Position to insert the item at (0-based index):</label><br>
<input type="number" id="position" name="position" min="0" required><br><br>
<input type="submit" value="Insert Item">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$arrayInput = filter_input(INPUT_POST, 'array', FILTER_SANITIZE_STRING);
$item = filter_input(INPUT_POST, 'item', FILTER_SANITIZE_STRING);
$position = filter_input(INPUT_POST, 'position', FILTER_VALIDATE_INT);
$array = array_map('trim', explode(',', $arrayInput));
if ($position >= 0 && $position <= count($array)) {
array_splice($array, $position, 0, $item);
echo "<h3>Updated Array:</h3>";
echo "<p>Original Array: " . htmlspecialchars($arrayInput) . "</p>";
echo "<p>Item Inserted: " . htmlspecialchars($item) . "</p>";
echo "<p>Position: " . htmlspecialchars($position) . "</p>";
echo "<p>New Array: " . htmlspecialchars(implode(', ', $array)) . "</p>";
} else {
echo "<p style='color: red;'>Invalid position!</p>";
}
}
?>
</body>
</html>
3. Write a program to sort the following associative array:
array(“Sophia”=>”31”,”Jacob”=>”41”,”William”=>”39”,”Ramesh”
=>”40”)in
a)Ascending order sort by value.
b)Ascending order sort by key.
c)Descending order sort by value.
d)Descending order sort by key.
e)Transform a string to all uppercase value.
f)Transform a string to all lowercase value.
g)Make a the keys so that the first character of each word is
uppercase.
<?php
$associativeArray = array(
"Sophia" => "31",
"Jacob" => "41",
"William" => "39",
"Ramesh" => "40"
);
echo "<h2>Original Array:</h2>";
echo "<pre>";
print_r($associativeArray);
echo "</pre>";
// (A) Sort the array by values in ascending order
asort($associativeArray);
echo "<h2>Sorted Array (Ascending by Value):</h2>";
echo "<pre>";
print_r($associativeArray);
echo "</pre>";
// (B) Sort the array by keys in ascending order
ksort($associativeArray);
echo "<h2>Sorted Array (Ascending by Key):</h2>";
echo "<pre>";
print_r($associativeArray);
echo "</pre>";
// (C) Sort the array by values in descending order
arsort($associativeArray);
echo "<h2>Sorted Array (Descending by Value):</h2>";
echo "<pre>";
print_r($associativeArray);
echo "</pre>";
// (D) Sort the array by keys in descending order
krsort($associativeArray);
echo "<h2>Sorted Array (Descending by Key):</h2>";
echo "<pre>";
print_r($associativeArray);
echo "</pre>";
// (E) Transform all keys and values to uppercase
$uppercaseArray = array();
foreach ($associativeArray as $key => $value) {
$uppercaseArray[strtoupper($key)] = strtoupper($value);
}
echo "<h2>Array with Uppercase Keys and Values:</h2>";
echo "<pre>";
print_r($uppercaseArray);
// (F) Transform all keys and values to lowercase
$lowercaseArray = array();
foreach ($associativeArray as $key => $value) {
// Transform key and value to lowercase
$lowercaseArray[strtolower($key)] = strtolower($value);
}
echo "<h2>Array with Lowercase Keys and Values:</h2>";
echo "<pre>";
print_r($lowercaseArray);
echo "</pre>";
// (G) Transform the keys so that the first character of each word is uppercase
$transformedArray = array();
foreach ($associativeArray as $key => $value) {
$newKey = ucwords($key);
$transformedArray[$newKey] = $value;
}
echo "<h2>Transformed Array with Capitalized Keys:</h2>";
echo "<pre>";
print_r($transformedArray);
echo "</pre>";
?>
4.Write a program using nested for loop that display a chess board.
<?php
echo '<html><body>';
echo '<table border="1" cellspacing="0" cellpadding="0">';
for ($row = 0; $row < 8; $row++) {
echo '<tr>';
for ($col = 0; $col < 8; $col++) {
$color = ($row + $col) % 2 == 0 ? 'white' : 'black';
echo '<td style="width: 50px; height: 50px; background-color: ' . $color . ';"></td>';
}
echo '</tr>';
}
echo '</table>';
echo '</body></html>';
?>
5.Write a program to compute and return the square root of a given number(Without
default array function)(Input get using form)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Square Root Calculator</title>
</head>
<body>
<h1>Square Root Calculator</h1>
<form action="index.php" method="post">
<label for="number">Enter a number:</label>
<input type="text" id="number" name="number" required>
<input type="submit" value="Calculate Square Root">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$number = filter_input(INPUT_POST, 'number', FILTER_VALIDATE_FLOAT);
if ($number !== false && $number >= 0) {
function computeSquareRoot($num) {
if ($num < 0) {
return "Invalid input. Number must be non-negative.";
}
$approx = $num;
$epsilon = 0.00001; // Precision level
while (abs($approx * $approx - $num) > $epsilon) {
$approx = ($approx + $num / $approx) / 2;
}
return $approx;
}
// Calculate and display the result
$squareRoot = computeSquareRoot($number);
echo "<p>The square root of $number is approximately $squareRoot.</p>";
} else {
echo "<p>Please enter a valid non-negative number.</p>";
}
}
?>
</body>
</html>
6.Write a program to print Fibonacci series using recursion.
<?php
function fibonacci($n) {
if ($n == 0) {
return 0;
} elseif ($n == 1) {
return 1;
} else {
return fibonacci($n - 1) + fibonacci($n - 2); // Recursive case
}
}
function printFibonacciSeries($n) {
for ($i = 0; $i < $n; $i++) {
echo fibonacci($i) . " ";
}
}
$n = 10;
echo "Fibonacci series up to $n terms: ";
printFibonacciSeries($n);
?>
7. Write a Program to validate given input is date or not and create simple "birthday
countdown' script,the script will count the number of days between current day and
birthday.
<!DOCTYPE html>
<html>
<head>
<title>Birthday Countdown</title>
</head>
<body>
<h2>Enter Your Birthday</h2>
<form method="post">
<label for="birthday">Birthday (YYYY-MM-DD):</label>
<input type="text" id="birthday" name="birthday" required>
<input type="submit" value="Calculate">
</form>
<?php
function validateDate($date, $format = 'Y-m-d') {
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) === $date;
}
function birthdayCountdown($birthday) {
$currentDate = new DateTime();
$birthdayThisYear = new DateTime(date('Y') . '-' . date('m-d', strtotime($birthday)));
// Check if birthday has already passed this year
if ($currentDate > $birthdayThisYear) {
// If passed, calculate for the next year
$birthdayNextYear = new DateTime((date('Y') + 1) . '-' . date('m-d',
strtotime($birthday)));
$interval = $currentDate->diff($birthdayNextYear);
} else {
// Calculate for the current year
$interval = $currentDate->diff($birthdayThisYear);
}
return $interval->days;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$inputDate = $_POST['birthday'];
if (validateDate($inputDate)) {
$daysLeft = birthdayCountdown($inputDate);
echo "<p>There are $daysLeft days left until your next birthday!</p>";
} else {
echo "<p>Invalid date format. Please enter a valid date in YYYY-MM-DD
format.</p>";
}
}
?>
</body>
</html>
8. Write a program to store current date-time in a COOKIE and displays the last,,Last
visited on "date - time on the web page upon reopening of the same page.
<?php
$cookieName = "lastVisit";
if(isset($_COOKIE[$cookieName])) {
$lastVisit = $_COOKIE[$cookieName];
echo "Last visited on: " . $lastVisit . "<br>";
} else {
echo "This is your first visit!<br>";
}
$currentDateTime = date("Y-m-d H:i:s");
setcookie($cookieName, $currentDateTime, time() + (86400 * 30));
echo "Current visit on: " . $currentDateTime;
?>
9. Upload and display images inn particular directory:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Upload</title>
</head>
<body>
<h2>Upload an Image</h2>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<label for="image">Choose an image:</label>
<input type="file" name="image" id="image" required>
<br><br>
<input type="submit" name="submit" value="Upload">
</form>
<?php
$target_dir = "uploads/";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!is_dir($target_dir)) {
mkdir($target_dir, 0777, true);
}
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$check = getimagesize($_FILES["image"]["tmp_name"]);
if ($check !== false) {
if (!file_exists($target_file) && $_FILES["image"]["size"] <= 5000000
&& in_array($imageFileType, ['jpg', 'png', 'jpeg', 'gif'])) {
if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
echo "The image ". htmlspecialchars(basename($_FILES["image"]["name"])) . "
has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
} else {
echo "File exists, is too large, or has an invalid format.";
}
} else {
echo "File is not an image.";
}
}
$images = glob($target_dir . "*.{jpg,jpeg,png,gif}", GLOB_BRACE);
if ($images) {
echo "<h3>Uploaded Images:</h3>";
foreach ($images as $image) {
echo "<img src='$image' alt='Image' style='width:200px; margin:10px;'><br>";
}
}
?>
</body>
</html>
10.To design an student details database using HTML Form and process using
PHP(Add,edit,delete ,view records)with login option.
student_db:
CREATE DATABASE student_db;
USE student_db;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
password VARCHAR(100) NOT NULL
);
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
age INT NOT NULL,
email VARCHAR(100),
course VARCHAR(50)
);
Users:
INSERT INTO users (username, password) VALUES ('admin', MD5('admin123'));
index.php:
<?php
session_start();
include('db.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = md5($_POST['password']);
$query = "SELECT * FROM users WHERE username='$username' AND
password='$password'";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) == 1) {
$_SESSION['username'] = $username;
header('Location: dashboard.php');
} else {
echo "Invalid username or password.";
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form method="post" action="index.php">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password" required><br>
<button type="submit">Login</button>
</form>
</body>
</html>
dashboard.php:
<?php
session_start();
if (!isset($_SESSION['username'])) {
header('Location: index.php');
exit();
include('db.php');
// Handle Add, Edit, Delete
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['add'])) {
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
$course = $_POST['course'];
$query = "INSERT INTO students (name, age, email, course) VALUES ('$name', '$age',
'$email', '$course')";
mysqli_query($conn, $query);
} elseif (isset($_POST['edit'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
$course = $_POST['course'];
$query = "UPDATE students SET name='$name', age='$age', email='$email',
course='$course' WHERE id=$id";
mysqli_query($conn, $query);
} elseif (isset($_POST['delete'])) {
$id = $_POST['id'];
$query = "DELETE FROM students WHERE id=$id";
mysqli_query($conn, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Dashboard</title>
</head>
<body>
<h2>Welcome, <?php echo $_SESSION['username']; ?>! <a
href="logout.php">Logout</a></h2>
<h3>Add New Student</h3>
<form method="post" action="dashboard.php">
Name: <input type="text" name="name" required><br>
Age: <input type="number" name="age" required><br>
Email: <input type="email" name="email"><br>
Course: <input type="text" name="course" required><br>
<button type="submit" name="add">Add Student</button>
</form>
<h3>Students List</h3>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Course</th>
<th>Actions</th>
</tr>
<?php
$query = "SELECT * FROM students";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<form method='post' action='dashboard.php'>";
echo "<td>{$row['id']}</td>";
echo "<td><input type='text' name='name' value='{$row['name']}' required></td>";
echo "<td><input type='number' name='age' value='{$row['age']}' required></td>";
echo "<td><input type='email' name='email' value='{$row['email']}'></td>";
echo "<td><input type='text' name='course' value='{$row['course']}' required></td>";
echo "<td>";
echo "<input type='hidden' name='id' value='{$row['id']}'>";
echo "<button type='submit' name='edit'>Edit</button>";
echo "<button type='submit' name='delete'>Delete</button>";
echo "</td>";
echo "</form>";
echo "</tr>";
?>
</table>
</body>
</html>
logout.php:
<?php
session_start();
session_destroy();
header('Location: index.php');
?>
db.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "student_db";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
?>
style.css:
/* General Styles */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
h2, h3 {
color: #333;
a{
text-decoration: none;
color: #fff;
padding: 8px 16px;
background-color: #333;
border-radius: 5px;
a:hover {
background-color: #555;
/* Container and Form Styling */
.container {
width: 80%;
margin: 0 auto;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
margin-top: 30px;
form {
margin-bottom: 20px;
label {
display: block;
margin-bottom: 8px;
color: #555;
input[type="text"], input[type="number"], input[type="email"], input[type="password"] {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 5px;
box-sizing: border-box;
}
button {
background-color: #28a745;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
button:hover {
background-color: #218838;
/* Table Styling */
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
table, th, td {
border: 1px solid #ddd;
th, td {
padding: 12px;
text-align: left;
th {
background-color: #f8f9fa;
color: #333;
tr:hover {
background-color: #f1f1f1;
/* Logout Link */
.logout {
float: right;
background-color: #dc3545;
.logout:hover {
background-color: #c82333;
/* Add some padding to the buttons in the form */
.form-buttons {
margin-top: 10px;
}
/* Responsive Design */
@media (max-width: 768px) {
.container {
width: 100%;
margin-top: 10px;
input[type="text"], input[type="number"], input[type="email"], input[type="password"] {
width: 100%;
11. To design an employee details database using HTML Form and process using
PHP(Add,Edit,View and delete records)with login option and some sample design
employee_db:
CREATE DATABASE employee_db;
USE employee_db;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
password VARCHAR(100) NOT NULL
);
CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
position VARCHAR(100),
department VARCHAR(100),
email VARCHAR(100),
phone VARCHAR(15)
);
User:
INSERT INTO users (username, password) VALUES ('admin', MD5('admin123'));
db.php:
<?php
$servername = "localhost";
$username = "root"; // XAMPP MySQL username
$password = ""; // Default is usually empty
$dbname = "employee_db"; // Your database name
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
?>
index.php:
<?php
session_start();
include('db.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = md5($_POST['password']);
$query = "SELECT * FROM users WHERE username='$username' AND
password='$password'";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) == 1) {
$_SESSION['username'] = $username;
header('Location: dashboard.php');
} else {
echo "<div class='container'><p style='color: red;'>Invalid username or
password.</p></div>";
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="container">
<h2>Login</h2>
<form method="post" action="index.php">
<label for="username">Username</label>
<input type="text" name="username" required>
<label for="password">Password</label>
<input type="password" name="password" required>
<button type="submit">Login</button>
</form>
</div>
</body>
</html>
dashboard.php:
<?php
session_start();
if (!isset($_SESSION['username'])) {
header('Location: index.php');
exit();
include('db.php');
// Handle Add, Edit, Delete
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['add'])) {
$name = $_POST['name'];
$position = $_POST['position'];
$department = $_POST['department'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$query = "INSERT INTO employees (name, position, department, email, phone)
VALUES ('$name', '$position', '$department', '$email', '$phone')";
mysqli_query($conn, $query);
} elseif (isset($_POST['edit'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$position = $_POST['position'];
$department = $_POST['department'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$query = "UPDATE employees SET name='$name', position='$position',
department='$department', email='$email', phone='$phone' WHERE id=$id";
mysqli_query($conn, $query);
} elseif (isset($_POST['delete'])) {
$id = $_POST['id'];
$query = "DELETE FROM employees WHERE id=$id";
mysqli_query($conn, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Dashboard</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="container">
<h2>Welcome, <?php echo $_SESSION['username']; ?>! <a href="logout.php"
class="logout">Logout</a></h2>
<h3>Add New Employee</h3>
<form method="post" action="dashboard.php">
<label for="name">Name</label>
<input type="text" name="name" required>
<label for="position">Position</label>
<input type="text" name="position" required>
<label for="department">Department</label>
<input type="text" name="department" required>
<label for="email">Email</label>
<input type="email" name="email" required>
<label for="phone">Phone</label>
<input type="text" name="phone" required>
<button type="submit" name="add">Add Employee</button>
</form>
<h3>Employee List</h3>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Position</th>
<th>Department</th>
<th>Email</th>
<th>Phone</th>
<th>Actions</th>
</tr>
<?php
$query = "SELECT * FROM employees";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<form method='post' action='dashboard.php'>";
echo "<td>{$row['id']}</td>";
echo "<td><input type='text' name='name' value='{$row['name']}' required></td>";
echo "<td><input type='text' name='position' value='{$row['position']}'
required></td>";
echo "<td><input type='text' name='department' value='{$row['department']}'
required></td>";
echo "<td><input type='email' name='email' value='{$row['email']}'
required></td>";
echo "<td><input type='text' name='phone' value='{$row['phone']}'
required></td>";
echo "<td>";
echo "<input type='hidden' name='id' value='{$row['id']}'>";
echo "<button type='submit' name='edit'>Edit</button>";
echo "<button type='submit' name='delete'>Delete</button>";
echo "</td>";
echo "</form>";
echo "</tr>";
?>
</table>
</div>
</body>
</html>
logout.php:
<?php
session_start();
session_destroy();
header('Location: index.php');
?>
style.css
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
h2, h3 {
color: #333;
}
.container {
width: 80%;
margin: 0 auto;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
margin-top: 30px;
form {
margin-bottom: 20px;
label {
display: block;
margin-bottom: 8px;
color: #555;
input[type="text"], input[type="email"], input[type="password"] {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 5px;
box-sizing: border-box;
button {
background-color: #28a745;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
button:hover {
background-color: #218838;
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
table, th, td {
border: 1px solid #ddd;
th, td {
padding: 12px;
text-align: left;
th {
background-color: #f8f9fa;
color: #333;
tr:hover {
background-color: #f1f1f1;
.logout {
float: right;
background-color: #dc3545;
.logout:hover {
background-color: #c82333;
@media (max-width: 768px) {
.container {
width: 100%;
margin-top: 10px;
}
}