Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Program 01

<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<script>
function validateForm() {
const email = document.getElementById('email').value;
const mobile = document.getElementById('mobile').value;
const textbox = document.getElementById('textbox').value;
let errorMessage = "";

// Validate email format


if (!validateEmail(email)) {
errorMessage += "Invalid email format.\n";
}

// Validate mobile number length


if (mobile.length !== 10) {
errorMessage += "Mobile number should be 10 characters.\n";
}

// Check if any field is left empty


if (email === "" || mobile === "" || textbox === "") {
errorMessage += "Please fill in all fields.\n";
}

// Display error message in an alert if any validation fails


if (errorMessage !== "") {
alert(errorMessage);
return false; // Prevent form submission
}

return true; // Allow form submission


}

// Function to validate email format using a regular expression


function validateEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
</script>
</head>
<body>
<h2>Form Validation</h2>
<form onsubmit="return validateForm()">
Email: <input type="text" id="email"><br><br>
Mobile Number: <input type="text" id="mobile"><br><br>
Textbox: <input type="text" id="textbox"><br><br>
Gender:
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female"> <label
for="female">Female</label><br><br>
Interests:
<input type="checkbox" id="music" name="interest" value="music">
<label for="music">Music</label>
<input type="checkbox" id="sports" name="interest" value="sports"> <label
for="sports">Sports</label><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Program 02

<!DOCTYPE html>
<html>
<head>
<title>Math Expression Evaluator</title>
<script>
function evaluateExpression() {
const expression = document.getElementById('expression').value;

try {
const result = eval(expression);
document.getElementById('result').textContent = `Result: ${result}`;
} catch (error) {
document.getElementById('result').textContent = "Invalid expression or operation.";
}
}
</script>
</head>
<body>
<h2>Math Expression Evaluator</h2>

<form>
Enter a mathematical expression:
<input type="text" id="expression">
<input type="button" value="Evaluate" onclick="evaluateExpression()">
</form>

<p id="result"></p>

</body>
</html>

Program 03

<!DOCTYPE html>
<html>
<head>
<title>Dynamic Effects with Layers and Basic Animation</title>
<style>
.layer {
position: absolute;
width: 100px;
height: 100px;
background-color: #3498db;
border-radius: 50%;
transition: all 0.5s ease-in-out;
}
</style>
</head>
<body>

<div class="layer" id="layer1"></div>


<div class="layer" id="layer2"></div>
<div class="layer" id="layer3"></div>

<script>
function moveLayers() {
const layer1 = document.getElementById('layer1');
const layer2 = document.getElementById('layer2');
const layer3 = document.getElementById('layer3');

// Change the position of layers using JavaScript


layer1.style.transform = "translate(150px, 150px)";
layer2.style.transform = "translate(300px, 300px)";
layer3.style.transform = "translate(450px, 450px)";
}

// Call the moveLayers function after a 1-second delay


setTimeout(moveLayers, 1000);
</script>

</body>
</html>

Program 04

<!DOCTYPE html>
<html>
<head>
<title>Sum of N Natural Numbers</title>
<script>
function sumOfNaturalNumbers(n) {
let sum = 0;
for (let i = 1; i <= n; i++) {
sum += i;
}
return sum; // Return sum after the loop completes
}

function calculateSum() {
const N = parseInt(document.getElementById('number').value);
if (!isNaN(N) && N > 0) {
const sum = sumOfNaturalNumbers(N);
document.getElementById('result').textContent = `The sum of first ${N} natural numbers is:
${sum}`;
} else {
document.getElementById('result').textContent = "Please enter a valid positive integer.";
}
}
</script>
</head>
<body>
<h2>Sum of N Natural Numbers</h2>
Enter a positive integer (N): <input type="text" id="number">
<button onclick="calculateSum()">Calculate</button>
<p id="result"></p>
</body>
</html>

Program 05

<!DOCTYPE html>
<html>
<head>
<title>Current Date in Words</title>
</head>
<body>

<h2>Current Date in Words</h2>


<p id="dateInWords"></p>

<script>
const daysOfWeek = [
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
];

const monthsOfYear = [
"January", "February", "March", "April", "May", "June", "July", "August", "September",
"October", "November", "December"
];

const currentDate = new Date();


const day = daysOfWeek[currentDate.getDay()];
const month = monthsOfYear[currentDate.getMonth()];
const year = currentDate.getFullYear();

const currentDateInWords = `${day}, ${month} ${currentDate.getDate()}, ${year}`;


document.getElementById('dateInWords').textContent = "Current date in words: " +
currentDateInWords;
</script>

</body>
</html>

Program 06

<!DOCTYPE html>
<html>
<head>
<title>Student Information Form</title>
<script>
function calculateResult() {
var math = parseFloat(document.getElementById('math').value);
var science = parseFloat(document.getElementById('science').value);
var english = parseFloat(document.getElementById('english').value);

var totalMarks = math + science + english;


var average = totalMarks / 3;

var result = (math >= 35 && science >= 35 && english >= 35) ? "Pass" : "Fail";

var grade;
if (average >= 90) {
grade = 'A+';
} else if (average >= 80) {
grade = 'A';
} else if (average >= 70) {
grade = 'B';
} else if (average >= 60) {
grade = 'C';
} else if (average >= 50) {
grade = 'D';
} else {
grade = 'F';
}

document.getElementById('totalMarks').value = totalMarks.toFixed(2);
document.getElementById('average').value = average.toFixed(2);
document.getElementById('result').value = result;
document.getElementById('grade').value = grade;
}
</script>
</head>
<body>

<h2>Student Information</h2>
<form>
Math: <input type="number" id="math"><br><br>
Science: <input type="number" id="science"><br><br>
English: <input type="number" id="english"><br><br>
<input type="button" value="Calculate" onclick="calculateResult()">
</form>
<br>

<h2>Result Details</h2>
Total Marks: <input type="text" id="totalMarks" readonly><br><br>
Average: <input type="text" id="average" readonly><br><br>
Result: <input type="text" id="result" readonly><br><br>
Grade: <input type="text" id="grade" readonly>

</body>
</html>

Program 07

<!DOCTYPE html>
<html>
<head>
<title>Employee Information Form</title>
<script>
function calculateSalary() {
var basicSalary = parseFloat(document.getElementById('basicSalary').value);
var allowance = parseFloat(document.getElementById('allowance').value);
var taxRate = parseFloat(document.getElementById('taxRate').value);

var DA = basicSalary * 0.25;


var HRA = basicSalary * 0.15;
var PF = basicSalary * 0.12;

var grossPay = basicSalary + DA + HRA + allowance;

var TAX = (grossPay - PF) * (taxRate / 100);


var deduction = PF + TAX;

var netPay = grossPay - deduction;

document.getElementById('DA').value = DA.toFixed(2);
document.getElementById('HRA').value = HRA.toFixed(2);
document.getElementById('PF').value = PF.toFixed(2);
document.getElementById('grossPay').value = grossPay.toFixed(2);
document.getElementById('deduction').value = deduction.toFixed(2);
document.getElementById('netPay').value = netPay.toFixed(2);
}
</script>
</head>
<body>

<h2>Employee Information</h2>

<form>
Basic Salary: <input type="number" id="basicSalary"><br><br>
Allowance: <input type="number" id="allowance"><br><br>
Tax Rate(%): <input type="number" id="taxRate"><br><br>
<input type="button" value="Calculate" onclick="calculateSalary()">
</form><br>

<h2>Salary Details</h2>

DA: <input type="text" id="DA" readonly><br><br>


HRA: <input type="text" id="HRA" readonly><br><br>
PF: <input type="text" id="PF" readonly><br><br>
Gross Pay: <input type="text" id="grossPay" readonly><br><br>
Deduction: <input type="text" id="deduction" readonly><br><br>
Net Pay: <input type="text" id="netPay" readonly>

</body>
</html>

Program 08

<?php

// Define an array to map days of the week to background colors


$dayColors = [
'Sunday' => '#ffcccb',
'Monday' => '#ffebcd',
'Tuesday' => '#add8e6',
'Wednesday' => '#98fb98',
'Thursday' => '#f0e68c',
'Friday' => '#dda0dd',
'Saturday' => '#c0c0c0'
];

// Get the current day of the week


$currentDay = date('l'); // Use 'l' for full day name

// Set a default color in case the day is not found


$backgroundColor = '#ffffff'; // Default white color

// Check if the current day exists in the array


if (array_key_exists($currentDay, $dayColors)) {
$backgroundColor = $dayColors[$currentDay]; // Use $currentDay consistently
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Background Color Based on Day of the Week</title>
<style>
body {
background-color: <?php echo $backgroundColor; ?>;
}
</style>
</head>
<body>
<h1>Welcome! Today is <?php echo $currentDay; ?></h1>
</body>
</html>

Program 09

<?php

function isPrime($num) {
if ($num <= 1) {
return false;
}

for ($i = 2; $i <= sqrt($num); $i++) {


if ($num % $i == 0) {
return false;
}
}

return true;
}

function generatePrimes($n) {
$primeNumbers = [];
$count = 0;
$i = 2;

while ($count < $n) {


if (isPrime($i)) {
$primeNumbers[] = $i;
$count++;
}
$i++;
}

return $primeNumbers;
}

function generateFibonacci($n) {
$fibonacciSeries = [];
$first = 0;
$second = 1;
$fibonacciSeries[] = $first;
$fibonacciSeries[] = $second;

for ($i = 2; $i < $n; $i++) {


$next = $first + $second;
$fibonacciSeries[] = $next;
$first = $second;
$second = $next;
}

return $fibonacciSeries;
}

$numberOfPrimes = 10;
$numberOfTerms = 10;

$primes = generatePrimes($numberOfPrimes);
$fibonacci = generateFibonacci($numberOfTerms);

echo "Prime numbers:";


echo "<pre>" . print_r($primes, true) . "</pre>";

echo "Fibonacci series:";


echo "<pre>" . print_r($fibonacci, true) . "</pre>";
?>
Program 10

<?php

function removeDuplicates($array) {
$result = array_values(array_unique($array));
return $result;
}

$sortedList = [1, 1, 2, 2, 3, 3, 4, 5, 5]; // Example sorted list

$uniqueList = removeDuplicates($sortedList);

echo "Original List: ";


print_r($sortedList);
echo "<br>Unique List: ";
print_r($uniqueList);

?>

Program 11

<?php

// Total number of rows for the pattern


$rows = 5;

for ($i = $rows; $i > 0; $i--) {

// Printing leading spaces


for ($j = $rows - $i; $j > 0; $j--) {
echo "&nbsp;"; // Non-breaking space for HTML output
}

// Printing asterisks
for ($k = 0; $k < $i; $k++) {
echo "*";
}

// Move to the next line


echo "<br>";
}

?>
Program 12

<?php

$data = [
['id' => 1, 'name' => 'Srikanth', 'age' => 30],
['id' => 2, 'name' => 'Srinath', 'age' => 35],
['id' => 3, 'name' => 'Srinivas', 'age' => 50],
['id' => 4, 'name' => 'Smayan', 'age' => 45],
['id' => 5, 'name' => 'Saatvik', 'age' => 50],
];

function searchByCriteria($data, $criteria) {


$results = [];

if (!is_array($data) || !is_array($criteria)) {
throw new InvalidArgumentException('Invalid data or criteria format (expected arrays)');
}

foreach ($data as $entry) {


$match = true;

if (!is_array($entry)) {
continue;
}

foreach ($criteria as $key => $value) {


if (!array_key_exists($key, $entry) || $entry[$key] != $value) {
$match = false;
break;
}
}

if ($match) {
$results[] = $entry;
}
}

return $results;
}
$criteria = ['age' => 50];

try {

$searchResults = searchByCriteria($data, $criteria);

echo "Search Results:\n";


print_r($searchResults);
} catch (InvalidArgumentException $e) {
echo "Error: " . $e->getMessage();
}

?>

Program 13

<?php

session_start();

function generateCaptchaCode($length = 6) {

$characters =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ;';

$charactersLength = strlen($characters);

$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}

return $randomString;
}

echo "Captcha Code is: " . generateCaptchaCode();

?>
Program 14

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<title>Image Upload and Display</title>

<h1>Upload and Display Images</h1>

<form method="post" enctype="multipart/form-data">

Select image to upload:


<input type="file" name="image" id="image">

<input type="submit" value="Upload Image" name="submit">

</form>

<h2>Uploaded Images:</h2>

<?php
// Connect to the database
$conn = new mysqli("localhost", "root", "", "myDB"); // Update with your credentials

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Function to display uploaded images


function displayImages($conn) {
$sql = "SELECT id, image_name FROM images";
$result = $conn->query($sql);

while ($row = $result->fetch_assoc()) {


echo "<img src='?id=" . $row["id"] . "' alt='" . $row["image_name"] . "'><br>";
}
}

// Image display logic (if GET request with 'id')


if (isset($_GET['id'])) {
$id = intval($_GET['id']);

$stmt = $conn->prepare("SELECT image_type, image_data FROM images WHERE id=?");


$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($imageType, $imageData);
$stmt->fetch();

header("Content-Type: " . $imageType);


echo $imageData;
exit;
}

// Image upload logic (if POST request with image)


if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_FILES["image"])) {
$imageData = file_get_contents($_FILES["image"]["tmp_name"]);
$imageName = $_FILES["image"]["name"];
$imageType = $_FILES["image"]["type"];

$stmt = $conn->prepare("INSERT INTO images (image_name, image_type, image_data)


VALUES (?, ?, ?)");
$stmt->bind_param("sss", $imageName, $imageType, $imageData);
$stmt->execute();
}

// Display uploaded images


displayImages($conn);

// Close the database connection


$conn->close();
?>

</body>
</html>

Program 15

<!DOCTYPE html>
<html>
<head>
<title>File Reader and Writer</title>
</head>
<body>

<form action="FileReadWrite.php" method="post">


<label for="userText">Enter Text: </label><br>
<textarea name="userText" id="userText"></textarea>
<input type="submit" value="Write to File"><br><br>
</form>

<form action="FileReadWrite.php" method="post" enctype="multipart/form-data">


<label for="filedata">Upload File to Read File Contents:</label><br>
<input type="file" name="filedata" id="filedata">
<input type="submit" value="Read File Contents"><br><br>
</form>

</body>
</html>

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
try {
if (!empty($_POST['userText'])) {
file_put_contents("output.txt", htmlspecialchars($_POST['userText']));
echo "Data written to file.";
}

if (!empty($_FILES['filedata']['tmp_name'])) {
$fileContent = file_get_contents($_FILES['filedata']['tmp_name']);
echo "File content: " . htmlspecialchars($fileContent) . "<br>";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
}

?>

Program 16

<?php
// Database connection details (replace with your actual credentials)
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Function to display student table with error handling


function displayStudents($conn) {
$sql = "SELECT * FROM student";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
echo "<table border='1'><tr><th>Reg
No</th><th>Name</th><th>Age</th><th>Course</th></tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr><td>" . htmlspecialchars($row["regno"]) . "</td><td>" .
htmlspecialchars($row["name"]) . "</td><td>" . $row["age"] . "</td><td>" .
htmlspecialchars($row["course"]) . "</td></tr>";
}
echo "</table>";
} else {
echo "No students found.";
}

$result->close(); // Close the result set (best practice)


}

// Process form submission


if ($_SERVER["REQUEST_METHOD"] == "POST") {
$regno = mysqli_real_escape_string($conn, $_POST['regno']); // Escape user input for
prepared statement
$name = mysqli_real_escape_string($conn, $_POST['name']); // Escape user input for
prepared statement
$age = $_POST['age'];
$course = mysqli_real_escape_string($conn, $_POST['course']); // Escape user input for
prepared statement
$action = $_POST['action'];

$stmt = null;
switch ($action) {
case 'add':
$sql = "INSERT INTO student (regno, name, age, course) VALUES (?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssss', $regno, $name, $age, $course);
break;
case 'update':
$sql = "UPDATE student SET name = ?, age = ?, course = ? WHERE regno = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('sssi', $name, $age, $course, $regno);
break;
case 'delete':
$sql = "DELETE FROM student WHERE regno = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $regno);
break;
}

if ($stmt) {
$stmt->execute();
$stmt->close(); // Close the prepared statement (best practice)

if ($conn->affected_rows > 0) {
echo "Operation successful.";
} else {
echo "No records affected.";
}
} else {
echo "Error: " . $conn->error;
}
}

// Display student table


displayStudents($conn);

// Close connection
$conn->close();
?>

<!DOCTYPE html>
<html>
<head>
<title>Student Database Management</title>
</head>
<body>
<h1>Manage Students</h1>
<form method="post">
Reg No: <input type="text" name="regno" required><br><br>
Name: <input type="text" name="name"><br><br>
Age: <input type="number" name="age"><br><br>
Course: <input type="text" name="course"><br><br>
<input type="submit" name="action" value="Add">
<input type="submit" name="action" value="Update">
<input type="submit" name="action" value="Delete">
</form>
</body>
</html>

Program 17

<!DOCTYPE html>

<html>

<head>

<title>Input Validation</title>

</head>

<body>

<form method="post">

Name: <input type="text" name="name"><br><br>

Email: <input type="text" name="email"><br><br>

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

</form>

</body>

</html>
<?php

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

$name = $_POST['name'];

$email = $_POST['email'];

if (empty($name)) {

echo "Name is required.<br><br>";

} else {

echo "Name: " .$name . "<br><br>";

if (empty($email)) {

echo "Email is required. <br><br>";

} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

echo "Invalid email format. <br><br>";

} else {

echo "Email:" .$email. "<br><br>";

?>

Program 18

<!DOCTYPE html>

<html>

<head>
<title>Cookie Handler</title>

</head>

<body>

<?php

// Check if the form has been submitted

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

// Set the cookie with a name and value from the form

setcookie("username", $_POST['username'], time() + (10*30), "/");

echo "<p>Cookie set. Reload the page to see the cookie value.</p>";
}
// Check if the cookie named "username" exists

if(isset($_COOKIE["username"])) {

echo "<p>Welcome back,". htmlspecialchars($_COOKIE["username"]). "!</p>";

} else {

echo "<p>Welcome, guest!</p>";

?>

<!-- HTML fors to set a cookie -->

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">


<label for="username">Enter yourname:</label><br>
<input type="text" id="username" name="username"><br>

<input type="submit" value="Set Cookie">

</form>

</body>
</html>

Program 19

Index.php

<!DOCTYPE html>

<html>

<head>

<title>Skyward Institute of Computer Applications</title>

<style>

body {

font-family: Arial, sans-serif;

header {

background-color: #f8f9fa;

padding: 20px;

text-align: center;

nav {

margin: 20px 0;

text-align: center;

}
nav a (

margin: 0 15px;

}
</style>

</head>

<body>

<header>

<img src="logo.jpg" alt="Skyward Institute of Computer Applications Logo" width="100">

<h1>Skyward Institute of Computer Applications</h1>

<p>157, 3RD MAIN, CHAMRAJPET BANGALORE 560018</p>

</header>

<nav>

<a href="index.php">Home</a>

<a href="about.php">About Us</a>

<a href="courses.php">Courses</a>

<a href="contact.php">Contact Us</a>

</nav>

<h2>Welcome to Skyward Institute of Computer Applications</h2>

<main>

<p>We provide best training on computer application courses.</p>

</main>

</body>

</html>

About.php
<!DOCTYPE html>

<html>

<head>

<title>About Us Skyward Institute of Computer Applications</title>

</head>

<body>

<h1>About Us</h1>

<p>Skyward Institute of Computer Applications was founded in 2010 with the aim to provide
quality education in the field of computer applications...</p>

</body>

</html>

Courses.php

<!DOCTYPE html>

<html>

<head>

<title>Courses

Skyward Institute of Computer Applications</title>

</head>

<body>

<h1>Courses</h1>

<h2>BCA</h2>

<h2>MCA</h2>
</body>

</html>

Contact.php

<!DOCTYPE html>

<html>

<head>

<title>Contact Us Skyward Institute of Computer Applications</title>

</head>

<body>

<h1>Contact Us</h1>

<p>Address: 157, 3RD MAIN, CHAMRAJPET BANGALORE 560018</p>

<p>Phone: +91-9611185999</p>

<p>Email: skyward.publishers@gmail.com</p>

</body>

</html>

Program 20

<?php

function divide($numerator, $denominator) {


if ($denominator == 0) {
throw new Exception("Cannot divide by zero.");
}
return $numerator / $denominator;
}

function checkDateFormat($date, $format = 'Y-m-d') {


$dateTime = DateTime::createFromFormat($format, $date);
if (!$dateTime || $dateTime->format($format) != $date) {
throw new Exception("Invalid date format.");
}
echo "The date " . $date . " is valid.<br>";
return true;
}

try {
echo divide(10, 2) . "<br>";
echo divide(10, 0) . "<br>";
} catch (Exception $e) {
echo "Division error: " . $e->getMessage() . "<br>";
}

try {
checkDateFormat("2023-03-10");
checkDateFormat("10/03/2023");
} catch (Exception $e) {
echo "Date error: " . $e->getMessage() . "<br>";
}

?>

You might also like