0% found this document useful (0 votes)
51 views32 pages

Practica 69

Uploaded by

jmegh03
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)
51 views32 pages

Practica 69

Uploaded by

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

Enrollment no.

:- 220840116069

Practical-7

Aim: Write programs using PHP.

7.1: Write a PHP program to find whether entered year is leap year or not.
Code:

<?php
$resultMessage = "";

/ /Check if the form has been submitted


if ($_SERVER["REQUEST_METHOD"] == "POST") {
$year = $_POST["year"];
if (checkLeapYear($year)) {
$resultMessage = "$year is a leap year.";
} else {
$resultMessage = "$year is not a leap year.";
}
}
// Function to check if a year is a leap year
function checkLeapYear($year) {
if (($year % 4 == 0 && $year % 100 != 0) || $year % 400 == 0) {
return true;
} else {
return false;
}
}
?>
<!-- HTML form to input the year -->
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
form {
max-width: 300px;
margin: 40px auto;
padding: 20px;
background-color: #fff;
border: 1px solid #ddd;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

84
Enrollment no. :- 220840116069

label {
display: block;
margin-bottom: 10px;
}
input[type="number"] {
width: 90%;
height: 40px;
margin-bottom: 20px;
padding: 10px;
border: 1px solid #ccc;
}
input[type="submit"] {
background-color: #4CAF50;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #3e8e41;
}
.result {
font-size: 18px;
font-weight: bold;
color: #00698f;
margin-top: 20px;
}
</style>

<form method="post">
<h2>Leap Year Checker</h2>
<label for="year">Enter a year:</label>
<input type="number" name="year" required>
<input type="submit" value="Check">
</form>

<!-- Display the result message -->


<?php if ($resultMessage): ?>
<center>
<p class="result"><?php echo $resultMessage; ?></p>
<?php endif; ?>

85
Enrollment no. :- 220840116069

Output:

86
Enrollment no. :- 220840116069

7.2: Write a PHP program to display table of cube for 1 to 10.


Code:

<?php
// Check if the form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Generate the table of cubes
$table = "<table border='1'>";
$table .= "<tr><th>Number</th><th>Cube</th></tr>";
for ($i = 1; $i <= 10; $i++) {
$cube = $i * $i * $i;
$table .= "<tr><td>$i</td><td>$cube</td></tr>";
}
$table .= "</table>";
// Display the table
$displayTable = true;
}
?>
<!-- HTML form to submit the request -->
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
form {
max-width: 300px;
margin: 40px auto;
padding: 20px;
background-color: #fff;
border: 1px solid #ddd;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
input[type="submit"] {
background-color: #4CAF50;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #3e8e41;
}

87
Enrollment no. :- 220840116069

.table-container {
margin-top: 20px;
}
</style>
<form method="post">
<h2>Table of Cubes</h2>
<input type="submit" value="Generate Table">
</form>
<!-- Display the table below the form -->
<?php if (isset($displayTable)): ?>
<center>
<div class="table-container">
<p>Table of Cubes:</p>
<?php echo $table; ?>
</div>
<?php endif; ?>

Output:

88
Enrollment no. :- 220840116069

7.3: Write a PHP program to read a text file and store it in array and display
the content of array.

Code:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fileName = "dummy.txt";
$fileContent = file($fileName, FILE_IGNORE_NEW_LINES);
$dataArray = array();

foreach ($fileContent as $line) {


$dataArray[] = $line;
}
$displayArray = true;
}
?>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
form {
max-width: 300px;
margin: 40px auto;
padding: 20px;
background-color: #fff;
border: 1px solid #ddd;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
input[type="submit"] {
background-color: #4CAF50;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #3e8e41;
}
.array-container {
margin-top: 20px;

89
Enrollment no. :- 220840116069

text-align: justify;
text-justify: inter-word;
}
</style>
<form method="post">
<h2>Read Text File and Display Array</h2>
<input type="submit" value="Read File and Display Array">
</form>
<?php if (isset($displayArray)): ?>
<div class="array-container">
<p>Array Content:</p>
<?php foreach ($dataArray as $element): ?>
<p><?= $element ?></p>
<?php endforeach; ?>
</div>
<?php endif; ?>

Output:

90
Enrollment no. :- 220840116069

7.4: Write PHP to store information of employee (employee id, job title, and
years of experience) in an array. And output the data to a web page by
arranging the employees in ascending order of experience.

Code:

<?php
$employees = array();
$displayEmployees = false;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the number of employees from the user
$numEmployees = $_POST['num_employees'];

// Loop through each employee and get their data from the user
for ($i = 0; $i < $numEmployees; $i++) {
$employeeId = $_POST["employee_id_$i"];
$jobTitle = $_POST["job_title_$i"];
$experience = $_POST["experience_$i"];

// Add employee data to the array


$employees[] = array('id' => $employeeId, 'job_title' => $jobTitle, 'experience' =>
$experience);
}

// Sort the employees array in ascending order of experience


usort($employees, function($a, $b) {
return $a['experience'] - $b['experience'];
});

$displayEmployees = true;
}
?>

<style>
/* Simple CSS styles */
body {
font-family: Arial, sans-serif;
margin: 20px;
background-color: #f4f4f4;
}

h2 {

91
Enrollment no. :- 220840116069

color: #333;
}

form {
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

table {
border-collapse: collapse;
width: 100%;
margin-top: 20px;
background-color: #fff;
}

th, td {
border: 1px solid #ddd;
padding: 10px;
text-align: left;
}

th {
background-color: #f2f2f2;
}

input[type="number"], input[type="text"] {
width: calc(100% - 20px);
padding: 10px;
margin-top: 5px;
border: 1px solid #ccc;
border-radius: 4px;
}

input[type="submit"] {
background-color: #4CAF50;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
}

92
Enrollment no. :- 220840116069

input[type="submit"]:hover {
background-color: #45a049;
}

.employee-input {
margin-bottom: 15px;
}
</style>

<form method="post">
<h2>Enter Employee Information</h2>
<p>Enter the number of employees:</p>
<input type="number" name="num_employees" required min="1">
<br><br>

<div id="employeeFields">
<!-- Employee input fields will be generated here -->
</div>

<input type="submit" value="Display Employee List">


</form>

<script>
const numEmployeesInput = document.querySelector('input[name="num_employees"]');
const employeeFieldsDiv = document.querySelector('#employeeFields');

numEmployeesInput.addEventListener('input', () => {
employeeFieldsDiv.innerHTML = '';
const numEmployees = numEmployeesInput.value;
for (let i = 0; i < numEmployees; i++) {
const employeeInputHtml = `
<div class="employee-input">
<p>Employee ${i + 1}:</p>
<input type="number" name="employee_id_${i}" placeholder="Employee ID"
required>
<input type="text" name="job_title_${i}" placeholder="Job Title" required>
<input type="number" name="experience_${i}" placeholder="Years of
Experience" required>
</div>
`;
employeeFieldsDiv.innerHTML += employeeInputHtml;
}
});
</script>

93
Enrollment no. :- 220840116069

<?php if ($displayEmployees): ?>


<table>
<tr>
<th>Employee ID</th>
<th>Job Title</th>
<th>Years of Experience</th>
</tr>
<?php foreach ($employees as $employee): ?>
<tr>
<td><?= htmlspecialchars($employee['id']) ?></td>
<td><?= htmlspecialchars($employee['job_title']) ?></td>
<td><?= htmlspecialchars($employee['experience']) ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>

Output:

94
Enrollment no. :- 220840116069

95
Enrollment no. :- 220840116069

7.5: Make a simple login form using cookie and session.

Code:

<?php
session_start();

if (isset($_POST['username']) && isset($_POST['password'])) {


$username = $_POST['username'];
$password = $_POST['password'];

if ($username == 'admin' && $password == '123') {


setcookie('username', $username, time() + 3600);
$_SESSION['username'] = $username;
header('Location: ' . $_SERVER['PHP_SELF']);
exit;
} else {
$error = 'Invalid username or password.';
}
}

if (isset($_GET['logout'])) {
setcookie('username', '', time() - 3600);
session_destroy();
header('Location: ' . $_SERVER['PHP_SELF']);
exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pr 7.5</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
}
.container {
width: 300px;
margin: 40px auto;

96
Enrollment no. :- 220840116069

padding: 20px;
background-color: #fff;
border: 1px solid #ddd;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
h2 {
color: #333;
margin-top: 0;
text-align: center;
}
.input-field {
margin-bottom: 20px;
display: flex;
align-items: center;
}
.input-field label {
width: 30%;
text-align: right;
margin-right: 10px;
}
input[type="text"], input[type="password"] {
width: 60%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
input[type="submit"] {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
width: 100%;
margin-top: 10px;
}
input[type="submit"]:hover {
background-color: #45a049;
}
.error-message {
color: red;
text-align: center;
margin-bottom: 20px;
}

97
Enrollment no. :- 220840116069

</style>
</head>
<body>
<div class="container">
<h2>Login Form</h2>
<?php if (isset($error)) echo "<p class='error-message'>$error</p>"; ?>

<?php if (isset($_SESSION['username'])): ?>


<p>Welcome, <?php echo $_SESSION['username']; ?>! You are now logged in.</p>
<a href="?logout=true">Logout</a>
<?php else: ?>
<form method="post">
<div class="input-field">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
</div>
<div class="input-field">
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</div>
<input type="submit" value="Login">
</form>
<?php endif; ?>
</div>
</body>
</html>

98
Enrollment no. :- 220840116069

Output:

99
Enrollment no. :- 220840116069

Practical-8

Aim : Develop applications using PHP and MYSQL

8.1: Make an application using PHP that collects student information like
name, PEN, Gender (use Radio Button), Branch (use Drop Down Box),
Semester, Contact number (Text Box should masked with numbers only)
and address. Create buttons for Insert, Delete, Update and Retrieve the
details in/from the database. Alter the table to add a column and add data in
that new column.

Code:

<?php
$servername = "localhost";
$username = "root"; // Your DB username
$password = ""; // Your DB password
$dbname = "student_db";

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

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

// Initialize variables to hold student data for retrieval


$students = [];
$operationMessage = '';

// Handle form submission


if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Use null coalescing operator to avoid undefined index notices
$name = $_POST['name'] ?? '';
$pen = $_POST['pen'] ?? '';
$gender = $_POST['gender'] ?? '';
$branch = $_POST['branch'] ?? '';
$semester = $_POST['semester'] ?? '';
$contact_number = $_POST['contact_number'] ?? '';
$address = $_POST['address'] ?? '';
$action = $_POST['action'] ?? '';

switch ($action) {
case 'insert':
$sql = "INSERT INTO students (name, pen, gender, branch, semester,
contact_number, address) VALUES ('$name', '$pen', '$gender', '$branch', $semester,
'$contact_number', '$address')";
100
Enrollment no. :- 220840116069

if ($conn->query($sql) === TRUE) {


$operationMessage = "New record created successfully.";
} else {
$operationMessage = "Error: " . $conn->error;
}
break;

case 'update':
$sql = "UPDATE students SET name='$name', gender='$gender', branch='$branch',
semester=$semester, contact_number='$contact_number', address='$address' WHERE
pen='$pen'";
if ($conn->query($sql) === TRUE) {
$operationMessage = "Record updated successfully.";
} else {
$operationMessage = "Error: " . $conn->error;
}
break;

case 'delete':
$sql = "DELETE FROM students WHERE pen='$pen'";
if ($conn->query($sql) === TRUE) {
$operationMessage = "Record deleted successfully.";
} else {
$operationMessage = "Error: " . $conn->error;
}
break;

case 'retrieve':
$sql = "SELECT * FROM students WHERE pen='$pen'";
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
$students = $result->fetch_all(MYSQLI_ASSOC);
$operationMessage = "Records retrieved successfully.";
} else {
$operationMessage = "No records found for PEN: $pen.";
}
break;
}
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Information</title>

101
Enrollment no. :- 220840116069

<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}

h1 {
color: #333;
margin-bottom: 10px;
}

form {
width: 50%;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

label {
display: block;
margin-bottom: 10px;
}

input[type="text"],
input[type="number"],
select,
textarea {
width: 100%;
padding: 10px;
margin-bottom: 20px;
border: 1px solid #ccc;
}

input[type="radio"] {
margin-right: 10px;
}

button[type="submit"] {
background-color: #4CAF50;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}

button[type="submit"]:hover {
background-color: #3e8e41;

102
Enrollment no. :- 220840116069

.message {
color: green;
font-weight: bold;
}

.error {
color: red;
font-weight: bold;
}
</style>
</head>

<body>
<h1>Student Information Form</h1>
<form action="" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name "><br>

<label for="pen">PEN:</label>
<input type="text" id="pen" name="pen"><br>

<label>Gender:</label>
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female <input type="radio"
name="gender" value="Other">
Other<br>

<label for="branch">Branch:</label>
<select id="branch" name="branch">
<option value="Computer Science">Computer Science</option>
<option value="Information Technology">Information Technology</option>
<option value="Electronics">Electronics</option>
<option value="Mechanical">Mechanical</option>
</select><br>

<label for="semester">Semester:</label>
<input type="number" id="semester" name="semester" min="1" max="8"><br>

<label for="contact_number">Contact Number:</label>


<input type="text" id="contact_number" name="contact_number" pattern="\d*"
maxlength="15"><br>

<label for="address">Address:</label>
<textarea id="address" name="address"></textarea><br>

<button type="submit" name="action" value="insert">Insert</button>


<button type="submit" name="action" value="update">Update</button>
<button type="submit" name="action" value="delete">Delete</button>

103
Enrollment no. :- 220840116069

<button type="submit" name="action" value="retrieve">Retrieve</button>


</form>

<?php if ($operationMessage): ?>


<p class="<?php echo strpos($operationMessage, 'Error') === 0 ? 'error' : 'message'; ?>">
<?php echo $operationMessage; ?>
</p>
<?php endif; ?>

<?php if (count($students) > 0): ?>


<h2>Student Records:</h2>
<ul>
<?php foreach ($students as $student): ?>
<li>PEN:
<?php echo $student['pen']; ?>, Name:
<?php echo $student['name']; ?>, Gender:
<?php echo $student['gender']; ?>, Branch:
<?php echo $student['branch']; ?>, Semester:
<?php echo $student['semester']; ?>, Contact:
<?php echo $student['contact_number']; ?>, Address:
<?php echo $student['address']; ?>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</body>

</html>

104
Enrollment no. :- 220840116069

Output:

105
Enrollment no. :- 220840116069

106
Enrollment no. :- 220840116069

107
Enrollment no. :- 220840116069

8.2: Customize your own WebPages/web application. You may use HTML,
Frame Navigation, CSS, JavaScript’s, PHP, Cookies, Session, MYSQL
Database Manipulation (Insert, Delete, Update and Retrieve), URL
Redirecting, File Uploads, and WEB SERVICES.

Code:

<?php
// Start session

session_start();

// Database connection
$conn = mysqli_connect("localhost", "root", "", "student_db");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// Initialize variables
$operationMessage = '';
$students = [];

// Handle form submissions


if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Handle user data
if (isset($_POST['name']) && isset($_POST['email'])) {
$name = $_POST['name'];
$email = $_POST['email'];

// Insert data into MySQL database


$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if (mysqli_query($conn, $sql)) {
$operationMessage = "New record created successfully";
} else {
$operationMessage = "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}

// Handle file upload


if (isset($_FILES['file'])) {
$file_name = $_FILES['file']['name'];
$file_tmp = $_FILES['file']['tmp_name'];
$operationMessage .= " File uploaded successfully.";
}

// Handle session

108
Enrollment no. :- 220840116069

$_SESSION['username'] = $name ?? 'Guest';


}

// Retrieve data from MySQL database


$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$students[] = $row;
}
}

// Close MySQL connection


mysqli_close($conn);
?>

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Web Application</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script>
// JavaScript code for form validation
function validateForm() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if (name == "" || email == "") {
alert("Name and email must be filled out");
return false;
}
return true;
}
</script>
<style>
body {
background-color: #f2f2f2;
font-family: Arial, sans-serif;
margin: 20px;
}

h1 {
color: #00698f;
}

label {
display: block;
margin-bottom: 10px;

109
Enrollment no. :- 220840116069

input[type="text"],
input[type="email"],
input[type="file"] {
width: 100%;
padding: 10px;
margin-bottom: 20px;
border: 1px solid #ccc;
}

input[type="submit"] {
background-color: #4CAF50;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}

input[type="submit"]:hover {
background-color: #3e8e41;
}

.message {
color: green;
font-weight: bold;
}

.error {
color: red;
font-weight: bold;
}
</style>
</head>

<body>
<h1>Welcome to My Web Application</h1>
<form action="" method="post" enctype="multipart/form-data" onsubmit="return
validateForm();">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>

<label for="email">Email:</label>
<input type="email" id="email" name="email" required>

<label for="file">Upload File:</label>


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

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

110
Enrollment no. :- 220840116069

</form>

<?php if ($operationMessage): ?>


<p class="<?php echo strpos($operationMessage, 'Error') === 0 ? 'error' : 'message'; ?>">
<?php echo $operationMessage; ?>
</p>
<?php endif; ?>

<h2>Student Records:</h2>
<ul>
<?php foreach ($students as $student): ?>
<li>Name:
<?php echo $student['name']; ?>, Email:
<?php echo $student['email']; ?>
</li>
<?php endforeach; ?>
</ul>

<p>Welcome,
<?php echo $_SESSION['username']; ?>!
</p>

<?php if (isset($_COOKIE['username'])): ?>


<p>Cookie found:
<?php echo $_COOKIE['username']; ?>!
</p>
<?php endif; ?>

<script>
// JavaScript code to handle web service
fetch('web_service.php', {
method: 'GET'
})
.then(response => response.json())
.then(data => console.log(data));
</script>
</body>

</html>

111
Enrollment no. :- 220840116069

Output:

112
Enrollment no. :- 220840116069

Practical-9

Aim: Write a program of hello world using jQuery and Ajax.

Code:

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pr9</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
body {
background-color: #f2f2f2;
font-family: Arial, sans-serif;
margin: 20px;
}

h1 {
color: #00698f;
text-align: center;
}

#helloButton {
display: block;
margin: 20px auto;
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
}

#helloButton:hover {
background-color: #45a049;
}

113
Enrollment no. :- 220840116069

#message {
margin-top: 20px;
padding: 15px;
background-color: #ffffff;
border: 1px solid #ccc;
border-radius: 5px;
text-align: center;
font-size: 18px;
color: #333;
}
</style>
<script>
$(document).ready(function () {
$("#helloButton").click(function () {
$.ajax({
url: 'hello.php',
type: 'GET',
success: function (response) {
$("#message").html(response);
},
error: function () {
$("#message").html("An error occurred while processing the request.");
}
});
});
});
</script>
</head>

<body>
<h1>Welcome to the Hello World Program</h1>
<button id="helloButton">Say Hello</button>
<div id="message"></div>
</body>

</html>

114
Enrollment no. :- 220840116069

Output:

115

You might also like