[go: up one dir, main page]

0% found this document useful (0 votes)
26 views41 pages

Lab Manual Web Programming

The document outlines a lab manual for a 5th semester BCA course, detailing various programming assignments and their corresponding marks allocation. It includes tasks related to HTML, JavaScript, and PHP, such as form validation, mathematical expression evaluation, and employee salary calculations. Each task is accompanied by example code snippets and expected outputs.

Uploaded by

hg0682276
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)
26 views41 pages

Lab Manual Web Programming

The document outlines a lab manual for a 5th semester BCA course, detailing various programming assignments and their corresponding marks allocation. It includes tasks related to HTML, JavaScript, and PHP, such as form validation, mathematical expression evaluation, and employee salary calculations. Each task is accompanied by example code snippets and expected outputs.

Uploaded by

hg0682276
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/ 41

STUDENT NAME:

SEMESTER:

SECTION:

COLLEGE ID:

REGISTER NUMBER:
MARKS ALLOCATION:

SL NO PARTICULARS TOTAL MARKS OBTAINED MARKS

1 INTERNAL ASSESSMENT 10

2 OBSERVATION BOOK 5

3 RECORD BOOK 10

4 EXECUTION 5

SUBJECT TEACHER HOD PRINCIPAL

WP-LAB MANUAL PROF. ANJALI SOMAN


5th SEMESTER BCA – BU NEP SYLLABUS 2021 Onwards
Sl. Completed Signature
No Experiment Date
1.
Create a form with the elements of Textboxes, Radio buttons,
Checkboxes, and so on. Write JavaScript code to validate the format in
email, and mobile number in 10 characters, if a textbox has been left
empty, popup an alert indicating when email, mobile number and
textbox has been left empty.
2. Develop an HTML form which accepts any mathematical expression. Write
a Javascript code to evaluate the expression.
3. Create a page with dynamic effects. Write the code to include layers and
basic animations.
4. Write a JavaScript code to find the sum of N natural numbers. (use user-
defined function)
5. Write a JavaScript code block using arrays and generate the current
date in words, this should include the day, month and year.
6. Create a form for Student information. Write JavaScript
code to find Total, Average, Result and Grade.
7.
Create a form for Employee information. Write JavaScript code to find
DA, HRA, PF, TAX, Gross pay, Deduction and Net pay.
8.
Write a program in PHP to change background color based on day of the
week using if else if statements and using arrays
9. Write a simple program in PHP for
1) Generating prime number.
2) Generate Fibonacci series.
10. Write a PHP program to remove duplicates from a sorted list.
11. Write a PHP Script to print the pattern on the Screen
12. Write a simple program in PHP for Searching of data by different criteria.
13. Write a function in PHP to generate a captcha code.
14. Write a Program to Store and read image from Database.
15. Write a program in PHP to read and write file using Form Control
16. Write a program in PHP to add, update and delete using student database.
17. Write a program in PHP to Validate Input
18. Write a program in PHP for setting and retrieving a cookie.
19. Write a PHP program to create a simple webpage of a college.
20. Write a program in PHP for exception handling for:
i) Divide by zero
ii) Checking date format

WP-LAB MANUAL PROF. ANJALI SOMAN


Programs:

1) Create a form with the elements of Textboxes, Radio buttons, Checkboxes, and so
on. Write JavaScript code to validate the format in email, and mobile number in 10
characters, if a textbox has been left empty, popup an alert indicating when email,
mobile number and textbox has been left empty.

<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<script>
function validateForm()
{
const email = document.
getElementById('email').value; const
mobile =
document.getElementById('mobile').val
ue; const textbox =
document.getElementById('textbox').value
; let isValid = true;
let errorMessage='';
// Validate email format
if(!validateEmail(email))
{
errorMessage+= "Invalid
email format.\n"; isValid
= false;
}
// Validate mobile
number length
if(mobile.length!==10)
{
errorMessage+="Mobile number should be 10
characters.\n"; isValid=false;
}
// Check if any field is left empty
if(email===''||mobile===''||textbox==='')
{
errorMessage+="Please fill in all
fields. \n"; isValid=false;
}
WP-LAB MANUAL PROF. ANJALI SOMAN
// Display error message in an alert if any
validation fails if(!isValid)
{
alert(errorMessage);
}
return isValid;
}
// 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> Address: <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>

WP-LAB MANUAL PROF. ANJALI SOMAN


OUTPUT:

WP-LAB MANUAL PROF. ANJALI SOMAN


2) Develop an HTML form which accepts any mathematical expression. Write a
JavaScript code to evaluate the expression and display the result.

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

WP-LAB MANUAL PROF. ANJALI SOMAN


OUTPUT:

3) Create a page with dynamic effects. Write the code to include layers and basic
animations.

<html>
<head>
<title> Basic Animation </title>
<style>
#layer1{position:absolute;
top:50px;left:50px;}
#layer2{position:absolute;
top:50px;left:400px;}
#layer3{position:absolute;
top:50px;left:800px;}
</style>

<script
type="text/javascript">
function
moveImage(layer)
{
var top = window.prompt("Enter top
value"); var left =
WP-LAB MANUAL PROF. ANJALI SOMAN
window.prompt("Enter left value");
document.getElementById(layer).style.top
=top+'px';
document.getElementById(layer).style.left
=left+'px';
}
</script>
</head>
<body>
<div id="layer1"><img src="ball.jpg" onclick="moveImage('layer1')" alt="My
Image."/></div>
<div id="layer2"><img src="ball.jpg" onclick="moveImage('layer2')" alt="My
Image."/></div>
<div id="layer3"><img src="ball.jpg" onclick="moveImage('layer3')" alt="My
Image."/></div>
</body>
</html>

OUTPUT:

WP-LAB MANUAL PROF. ANJALI SOMAN


4) Write a Javascript code to find the sum of N natural numbers. Use user-defined
function.
<html>
<head>
<title>sum of n numbers</title>
<script
type="text/javascript"
> function sum()
{
var n=prompt("enter a
number",0); var
num=parseInt(n);
var sum=0;
for(i=1;i<=num;i++)
{
sum=sum+i;
}
document.writeln("sum of "+num+" natural numbers: "+sum);
}
</script>

</head>
<body>
<center><h1> finding sum of natural numbers using javascript </h1>
WP-LAB MANUAL PROF. ANJALI SOMAN
<input type="button" onclick="sum()" value="sum"/>
</center>
</body>
</html>

OUTPUT:

WP-LAB MANUAL PROF. ANJALI SOMAN


5) Write a JavaScript code block using arrays and generate the current date in words,
this should include the day, month and year.
<!DOCTYPE html>
<html>
<title>Current Date in Words</title>
<head>
</head>
<body>
<h2>Current Date in Words</h2>
<p id="dateInWords"></p><script>
// Arrays to hold day, month,
and year names const
daysOfWeek = [
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
];
const monthsOfYear = [
"January", "February", "March", "April", "May", "June", "July", "August", "September",
"October", "November", "December"];
// Get current date
const currentDate = new Date();
// Extract day, month, and year components
const day = daysOfWeek [currentDate.getDay()]; const month = monthsOfYear
[currentDate.getMonth()]; const year = currentDate.getFullYear();
// Construct the date in words
const currentDateInWords = `${day}, ${month} ${currentDate.getDate()},
${year}`;
// Display the date in words
document.getElementById('dateInWords').textContent = "Current date in words: " +
currentDateInWords;
</script>
</body>
</html>

WP-LAB MANUAL PROF. ANJALI SOMAN


OUTPUT:

6) Create a form for Student information. Write JavaScript code to find Total,
Average, Result and Grade.

<html>
<head>
<title>Student Information Form</title>
<script>
function calculateResult() {
// Get input values from the form
var math=parseFloat(document.getElementById('math').value);
var
science=parseFloat(document.getElementById('s
cience').value); var
english=parseFloat(document.getElementById('en
glish').value);
// Calculate Total
marks and Average
var
totalMarks=math+sci
ence+english; var
average=totalMarks/
WP-LAB MANUAL PROF. ANJALI SOMAN
3;
var result=(math>=35 && science>=35 && english>=35)?"Pass":"Fail";
// Calculate Grade based on the
average marks 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';
}
// Display the calculated values
document.getElementById('totalMarks').value=totalMark
s.toFixed(2);
document.getElementById('average').value=average.to
Fixed(2);
document.getElementById('result').value=r
esult;
document.getElementById('grade').value=g
rade;
}

WP-LAB MANUAL PROF. ANJALI SOMAN


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

OUTPUT:

WP-LAB MANUAL PROF. ANJALI SOMAN


7) Create a form for Employee information. Write JavaScript code to find DA, HRA,
PF, TAX, Gross pay, Deduction and Net pay.
<html>
<head>
<script type="text/javascript">
function show()
{
var name=document.getElementById("txtname").value;
var num=document.getElementById("txtnum").value;
var sal=parseInt(document.getElementById("txtsal").value);
var hra=(sal*40)/100;
var da=(sal*60)/100;
var gross=sal+hra+da;
var pf=(sal*13)/100;
var tax=(sal*20)/100;
var deduct=pf+tax;
var net=gross-deduct;
document.writeln("<b>Employee Name:"+name+"</b>"+"<br>"+"<br>");
document.writeln("<b>Employee Number:"+num+"</b>"+"<br>"+"<br>");
document.writeln("<b>Basic salary:"+sal+"</b>"+"<br>"+"<br>");
document.writeln("<b>HRA:"+hra+"</b>"+"<br>"+"<br>");
document.writeln("<b>DA:"+da+"</b>"+"<br>"+"<br>");
document.writeln("<b>Gross Salary:"+gross+"</b>"+"<br>"+"<br>");
document.writeln("<b>PF:"+pf+"</b>"+"<br>"+"<br>");
document.writeln("<b>Tax:"+tax+"</b>"+"<br>"+"<br>");
document.writeln("<b>Deduction:"+deduct+"</b>"+"<br>"+"<br>");
document.writeln("<b>Net Salary:"+net+"</b>"+"<br>"+"<br>");
}

WP-LAB MANUAL PROF. ANJALI SOMAN


</script>
</head>
<body background="#3f2" text="blue">
<center>
<h1> Employee Detail Form</h1>
<form name="emp">
<table border="2">
<tr><td colspan="2" align="center"> Employee Detail:</td></tr><br>
<tr><td>Employee Name:</td><td><input type="text" id="txtname"></td></tr><br>
<tr><td>Employee Number:</td><td><input type="text" id="txtnum"></td></tr><br>
<tr><td> Basic Salary:</td><td><input type="text" id="txtsal"></td></tr><br>
<tr><td><input type="button" onclick="show()" value="Salary Report"></td>

<td><input type="reset" value="Reset"></td></tr>


</table>
</form>
</center>
</body>
</html>

WP-LAB MANUAL PROF. ANJALI SOMAN


WP-LAB MANUAL PROF. ANJALI SOMAN
8) Write a program in PHP to change background color based on day of the week using
if else if statements and using arrays

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

// 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)) {
// If the day exists, set the background color based on the day
$backgroundColor = $dayColors[$currentDay];
}
?>
<!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>

WP-LAB MANUAL PROF. ANJALI SOMAN


OUTPUT:

WP-LAB MANUAL PROF. ANJALI SOMAN


9) Write a simple program in PHP for
3) Generating prime number.
4) Generate Fibonacci series.
<?php
$count = 0;
$num = 2;
echo "<h3>Prime numbers from
1 to 50: </h3>"; echo "\n";
while ($count < 15 )
{
$div_count=0;
for ( $i=1; $i<=$num; $i++)
{
if (($num%$i)==0)
{
$div_count++;
}}
if ($div_count<3)
{
echo $num." , ";
$count=$count+1;
}
$num=$num+1;
?>
<?php
$num = 0;
$n1 = 0;
$n2 = 1;
echo "<h3>Fibonacci series for first 12
numbers: </h3>”;
echo “\n”;
echo $n1.’’.$n2.’’;
while($num<10){
$n3=$n2+$n1;
echo $n3.’’;
$n1=$n2;
$n2=$n3;
$num=$num+1; }?>

OUTPUT:

WP-LAB MANUAL PROF. ANJALI SOMAN


10) Write a PHP program to remove duplicates from a sorted list.

<html>
<head>
<title> Remove duplicates from sorted list</title>
</head>
<body>
<h2> Enter a sorted list of numbers separated by spaces</h2>
<form method="post">
<input type="text" name="numbers" placeholder="enter numbers">
<input type="submit" name="submit" value="remove duplicates">
</form>
<?php
function removeDuplicates($arr){
$n=coun
t($arr);
if($n==0
||$n==1)
{ return
$arr;
}
$unique=[];
$unique[
]=$arr[0]
;
for($i=1;
$i<$n;$i
++){
if($arr[$i]
!=$arr[$i-
1]){
$unique[]=$arr[$i];
}

WP-LAB MANUAL PROF. ANJALI SOMAN


}
return $unique;
}
if($_SERVER["REQUEST_METHO
D"]=="POST"){
$input=$_POST["numbers"];
$inputArray=explode(" ",$input);
$sortedList=array_map('intv
al',$inputArray);
sort($sortedList);
echo"<h2> Entered List:</h2>";
echo "<pre>".print_r($sortedList,true)."</pre>";
$result=removeDuplicates($sortedLi
st); echo"<h2>List after removing
duplicates:</h2>";
echo"<pre>".print_r($result,true)."</
pre>";
}
?>
</body></html>

OUTPUT:

11) Write a PHP Script to print the following pattern on the Screen:

WP-LAB MANUAL PROF. ANJALI SOMAN


*****
****
***
**
*
<?php
$rows=5;
for($i=$rows;$
i>=1;$i--){
for($j=$rows;
$j>$i;$j--){
echo"&nbsp;"
;
}
for($k=1;$k<=$i;$
k++){ echo"*";
}
echo"<br>";
}
?>
OUTPUT:

12) Write a simple program in PHP for Searching of data by different criteria.

WP-LAB MANUAL PROF. ANJALI SOMAN


<?php
$user=[
['id'=>1,'name'=>'Anjali','age'=>20,'email'=>'anjali@example.com'],['id'=>2,'name'=>'Neena','ag
e'=>19,'em
ail'=>'Neena@example.com'],['id'=>3,'name'=>'Madhu','age'=>22,'email'=>'madhu@example.co
m'],['id'=>4
,'name'=>'Vinay','age'=>21,'email'=>'vinay@ex
ample.com']]; function
searchdata($data,$criteria,$value){
$results=[];
foreach($d
ata as
$item){
if($item[$criteria]==$value){
$results[]=$item;
}
}
return $results;
}
$searchCriteria='age';
$searchValue=19;
$searchResults=searchData($user,$searchCriteria,$se
archValue); echo "Search Results for
$searchCriteria=$searchValue:<br>";
if(count($searchResults)>0){
foreach($searchResults as $result){
echo
"ID:".$result['id'].".Name:".$result['name'].",Age:".$result['age'].",Email:".$result['email']."<b
r>";
}
}else {
echo " No results found.";
}
?>

OUTPUT:

WP-LAB MANUAL PROF. ANJALI SOMAN


13) Write a function in PHP to generate a captcha code.
<?php
function generateCaptcha($length=6){
$characters='ABCDEFGHIJKLOMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012
3456789';
$captcha='';
$charLength=strlen($charact
ers);
for($i=0;$i<$length;$i++){
$captcha.=$characters[rand(0,$charLength-1)];
}
$_SESSION['captcha'
]=$captcha; return
$captcha;
}
session_start();
$captchaCode=generateCaptcha(6);
echo "Generated Captcha: $captchaCode";
?>

OUTPUT:

WP-LAB MANUAL PROF. ANJALI SOMAN


14) Write a Program to Store and read image from Database .
<?php
$conn = new mysqli("localhost", "root", "", "myDB");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Display Image
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;
}
// Upload 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();
}

WP-LAB MANUAL PROF. ANJALI SOMAN


// Display 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>";
}
}
?>
<!DOCTYPE html>
<html>
<head><title>Image Upload and Display</title></head>
<body>
<h1>Upload and Display Images</h1>
<form method="post" enctype="multipart/form-data">

Select image to upload:<br>


<input type="file" name="image" id="image"><br>
<input type="submit" value="Upload Image" name="submit">
</form>

<h2>Uploaded Images:</h2>
<?php displayImages($conn); ?>
<?php $conn->close(); ?>
</body>
</html>
<!DOCTYPE html>

WP-LAB MANUAL PROF. ANJALI SOMAN


<html>
<head><title>File Reader and Writer</title></head>
<body>
<form action="FileReadWrite.php" method="post">
<label for="textdata">Enter text:</label><br>
<textarea name="textdata" id="textdata"></textarea><br>
<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"><br>
<input type="submit" value="Read File Contents"><br><br>
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST['textdata'])) {
file_put_contents("output.txt", $_POST['textdata']);
echo "Data written to file.<br>";
}

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

WP-LAB MANUAL PROF. ANJALI SOMAN


</body>
</html>
OUTPUT:

15) Write a program in PHP to read and write file using Form Control
<!DOCTYPE html>
<html>
<head>
<title>File Reader and Writer</title>
</head>
<body>
<form action="FileReadWrite.php" method="post">
<label for="textdata">Enter text</label><br>

WP-LAB MANUAL PROF. ANJALI SOMAN


<textarea name="textdata" id="textdata"></textarea><br>
<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"><br>
<input type="submit" value="Read File Contents"><br><br>
</form>
</body>
</html>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST["textdata"])) {
file_put_contents("output.txt", $_POST["textdata"]);
echo "Data written to file.<br>";
}
if (!empty($_FILES["filedata"]["tmp_name"])) {
$fileContent = file_get_contents($_FILES["filedata"]["tmp_name"]);
echo "File content: " . htmlspecialchars($fileContent) . "<br>";
}
}
?>

OUTPUT:

WP-LAB MANUAL PROF. ANJALI SOMAN


16) Write a program in PHP to add, update and delete using student database.
STEPS TO SETUP :

1. Start WAMP Server:


- Launch WAMP Server. Ensure all services (Apache, MySQL) are running.
2. Create a Database and Tables:
- Open phpMyAdmin in web browser (http://localhost/phpmyadmin/)
- The default username for phpMyAdmin in WAMP Server is usually root, and by default,
there is no password.
- Create a new database called myDB.
- Create a student table under myDB database. (use 4 columns)
regno (primary key) - INT
name - varchar(50)
age - INT
course - varchar(50)

<?php
$conn = new mysqli("localhost", "root", "", "myDB"); // Establish connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); // Connection error
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$regno = $_POST["regno"];
$name = $_POST["name"];
$age = $_POST["age"];
$course = $_POST["course"];

switch ($_POST["action"]) {
case "Add":
$sql = "INSERT INTO student VALUES ('$regno','$name','$age','$course')";
break;

WP-LAB MANUAL PROF. ANJALI SOMAN


case "Update":
$sql = "UPDATE student SET name='$name', age='$age', course='$course' WHERE
regno='$regno'";
break;
case "Delete":
$sql = "DELETE FROM student WHERE regno='$regno'";
break;
}
if ($conn->query($sql) === FALSE) {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Function to display students
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>" . $row["regno"] . "</td><td>" . $row["name"] . "</td><td>" . $row["age"] .
"</td><td>" . $row["course"] . "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
?>
<!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">

WP-LAB MANUAL PROF. ANJALI SOMAN


</form>
<?php
displayStudents($conn); // Display students
$conn->close(); // Close connection
?>
</body>

</html>

OUTPUT:

WP-LAB MANUAL PROF. ANJALI SOMAN


17) Write a program in PHP to Validate Input
<!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)) {

WP-LAB MANUAL PROF. ANJALI SOMAN


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

OUTPUT:

18) Write a program in PHP for setting and retrieving a cookie.

<?php
$cookie_name="UserID";
$cookie_value="ABCD";

WP-LAB MANUAL PROF. ANJALI SOMAN


$expiration_time=time()+(24*3600);
setcookie($cookie_name,$cookie_value,$ex
piration_time,"/"); echo "cookie
'$cookie_name' is set.<br><br><br>";
if(isset($_COOKIE[$cookie_name]))
{
echo "value of cookie '$cookie_name' is:".$_COOKIE[$cookie_name];
}
else
{
echo "Cookie named '$cookie_name' is not set.";
}
?>

OUTPUT:

19) Write a PHP program to create a simple webpage of a college.


<html>
<head>
<title>College Website</title>
<! CSS styles can be added here >
style> body {
font_family:Arial,sans
-serif; margin:20px;
}
h1 { color:#333;
}

WP-LAB MANUAL PROF. ANJALI SOMAN


p {color:#666;
}
</style>
</head>
<body>
<header>
<h1>Welcome to Our College</h1>
</header>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Courses</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
<main>
<section>
<h2>About Our College </h2>
<p>This is a brief description of our college.</p>
</section>
<h2>Available Courses</h2>
<?php
$courses=['Computer Science', 'Engineering',
'Business', 'Arts', 'Science']; echo"<ul>";

foreach($courses as $course)
{
echo"<li>$course</li>";
}
echo"</ul>";
?>
</section>
<section>
<h2>Contact Information</h2>
<p>Address:123 College Avenue,City,Country</p>
<p>Email:info@college.com</p>
<p>Phone:080-25634869</p>
</section>
</main>

WP-LAB MANUAL PROF. ANJALI SOMAN


<footer>
<p>&copy;
<?php
echo date("Y");
?>
Our College.All rights reserved.</p>
</footer>
</body>

</html>

20) Write a program in PHP for exception handling for :


a. Divide by zero
b. Checking date format.

<?php try {
$numerator=10;
$denominator=2;
if($denominator
===0) {
throw new Exception("Division by zero error");
}
$result=$numerator/$
denominator;
echo"Result of
division:".$result."<br
WP-LAB MANUAL PROF. ANJALI SOMAN
>";
$dateString='2023-12-25';
$dateFormat='Y-m-d';
$date=DateTime::createFromFormat($dateF
ormat,$dateString); if(!$date||$date-
>format($dateFormat)!==$dateString) {
throw new Exception("Invalid date format");
}
echo"Date is valid:".$dateString;
}
catch(Excep
tion $e) {
echo"Error:".$e
-
>getMessage();
}
?

OUTPUT:

WP-LAB MANUAL PROF. ANJALI SOMAN

You might also like