0% found this document useful (0 votes)
357 views48 pages

Php&mysql-Lab Manual

Uploaded by

ddugky.alg
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)
357 views48 pages

Php&mysql-Lab Manual

Uploaded by

ddugky.alg
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/ 48

Course 7A: Web Applications Development using PHP & MYSQL

LAB-PROGRAMS

1. Write a PHP program to Display “Hello”?

<?php
// Display the text "Hello"
echo "Hello";
?>

Output: Hello

2. Write a PHP Program to display the today’s date?

<?php
// Display today's date
echo date("Y-m-d");
?>

Output: 2024-09-15
Note: This code will output the current date in the format YYYY-MM-DD. The date()
function formats the current date according to the specified format.

3. Write a PHP program to display Fibonacci series?

What is the Fibonacci Series?

The Fibonacci series is a sequence of numbers where each number is the sum of the
two numbers before it.

How Does It Work?

1. Start with the First Two Numbers:


o The sequence begins with 0 and 1. These are the first two numbers in
the series.
2. Add the Last Two Numbers:
o To find the next number in the sequence, add the last two numbers
together.
3. Continue the Pattern:
o Keep repeating the process: add the last two numbers to get the next
number.

Example: Let's build the Fibonacci series step-by-step:

1. Start:
o 0, 1
2. Next Number:
o Add 0 and 1 to get 1.
o Sequence: 0, 1, 1
3. Continue:
o Add 1 and 1 to get 2.
o Sequence: 0, 1, 1, 2
4. Next:
o Add 1 and 2 to get 3.
o Sequence: 0, 1, 1, 2, 3
5. Continue:
o Add 2 and 3 to get 5.
o Sequence: 0, 1, 1, 2, 3, 5

<?php
// Number of terms to display
$n = 10;
// Initialize the first two terms
$first = 0;
$second = 1;
// Display the Fibonacci series
echo "Fibonacci Series up to $n terms: <br>";

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


echo $first . " ";
$next = $first + $second;
$first = $second;
$second = $next;
}
?>

Output: Fibonacci Series up to 10 terms:


0 1 1 2 3 5 8 13 21 34
4. Write a PHP Program to read the employee details?

Here's a simple PHP program to read and display employee details using an HTML
form. This program assumes you're submitting data via a form.

1. Create an HTML form to input employee details: (form.html)

<!-- save this as form.html -->


<html>
<head>
<title>Employee Details Form</title>
</head>
<body>
<h1>Employee Details</h1>
<form action="process.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>

<label for="id">Employee ID:</label>


<input type="text" id="id" name="id" required><br><br>

<label for="position">Position:</label>
<input type="text" id="position" name="position"
required><br><br>

<label for="department">Department:</label>
<input type="text" id="department" name="department"
required><br><br>

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


</form>
</body>
</html>
2. Create a PHP script to process and display the submitted data:

<!-- save this as process.php -->


<?php
// Get employee details from form submission
$name = $_POST['name'];
$id = $_POST['id'];
$position = $_POST['position'];
$department = $_POST['department'];

// Display employee details


echo "<h1>Employee Details</h1>";
echo "<p><strong>Name:</strong> " . htmlspecialchars($name) . "</p>";
echo "<p><strong>Employee ID:</strong> " . htmlspecialchars($id) .
"</p>";
echo "<p><strong>Position:</strong> " . htmlspecialchars($position) .
"</p>";
echo "<p><strong>Department:</strong> " . htmlspecialchars($department)
. "</p>";
?>
Output:

How to Use:

1. Save the HTML form as form.html and the PHP script as process.php on your PHP-
enabled server.
2. Open form.html in your web browser, fill in the details, and submit the form.
3. The process.php script will process the data and display the employee details.

5. Write a PHP program to prepare the student marks list?

Here’s a simple PHP program to prepare and display a student marks list. This
example assumes the marks are input via an HTML form and then processed by a
PHP script.

1. Create an HTML form to input student marks: (marks_form.html)

<!-- save this as marks_form.html -->

<html>
<head>
<title>Student Marks Form</title>
</head>
<body>
<h1>Enter Student Marks</h1>
<form action="process_marks.php" method="post">
<label for="name">Student Name:</label>
<input type="text" id="name" name="name"
required><br><br>

<label for="math">Math:</label>
<input type="number" id="math" name="math"
required><br><br>

<label for="english">English:</label>
<input type="number" id="english" name="english"
required><br><br>

<label for="science">Science:</label>
<input type="number" id="science" name="science"
required><br><br>

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


</form>
</body>
</html>

2. Create a PHP script to process and display the Student Marks:


(process_marks.php)
<!-- save this as process_marks.php -->
<?php
// Get student details from form submission
$name = $_POST['name'];
$math = $_POST['math'];
$english = $_POST['english'];
$science = $_POST['science'];

// Calculate total and average marks


$total = $math + $english + $science;
$average = $total / 3;
// Display student marks
echo "<h1>Student Marks List</h1>";
echo "<p><strong>Student Name:</strong> " . htmlspecialchars($name) .
"</p>";
echo "<p><strong>Math:</strong> " . htmlspecialchars($math) . "</p>";
echo "<p><strong>English:</strong> " . htmlspecialchars($english) .
"</p>";
echo "<p><strong>Science:</strong> " . htmlspecialchars($science) .
"</p>";
echo "<p><strong>Total Marks:</strong> " . htmlspecialchars($total) .
"</p>";
echo "<p><strong>Average Marks:</strong> " .
htmlspecialchars(number_format($average, 2)) . "</p>";
?>

Output:
How to Use:

1. Save the HTML form as marks_form.html and the PHP script as process_marks.php
on your PHP-enabled server.
2. Open marks_form.html in your web browser, fill in the details, and submit the form.
3. The process_marks.php script will process the data and display the student marks
list.

6. Write a PHP program to generate the multiplication of two matrices?

<?php
// Function to multiply two matrices
function multiplyMatrices($matrix1, $matrix2) {
$result = [];
for ($i = 0; $i < count($matrix1); $i++) {
for ($j = 0; $j < count($matrix2[0]); $j++) {
$result[$i][$j] = 0;
for ($k = 0; $k < count($matrix2); $k++) {
$result[$i][$j] += $matrix1[$i][$k] * $matrix2[$k][$j];
}
}
}
return $result;
}

// Define two matrices


$matrix1 = [[1, 2, 3], [4, 5, 6]];
$matrix2 = [[7, 8], [9, 10], [11, 12]];

// Multiply and display result


$result = multiplyMatrices($matrix1, $matrix2);
foreach ($result as $row) {
echo implode(" ", $row) . "<br>";
}
?>
Output: 58 64
139 154
7. Create student registration form using text box, check box, radio button, select,
submit button. And display user inserted value in new PHP page.

Here's a simple PHP program for creating a student registration form and displaying
the submitted values on another page:

1. registration_form.html - The Registration Form:


<html>
<head>
<title>Student Registration Form</title>
</head>
<body>
<h2>Student Registration</h2>
<form action="display_values.php" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>

<label for="gender">Gender:</label>
<input type="radio" id="male" name="gender"
value="Male"> Male
<input type="radio" id="female" name="gender"
value="Female"> Female<br><br>

<label for="subjects">Subjects:</label><br>
<input type="checkbox" name="subjects[]" value="Maths">
Maths<br>
<input type="checkbox" name="subjects[]" value="Science">
Science<br>
<input type="checkbox" name="subjects[]" value="English">
English<br><br>

<label for="grade">Grade:</label>
<select id="grade" name="grade">
<option value="10th">10th</option>
<option value="11th">11th</option>
<option value="12th">12th</option>
</select><br><br>

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


</form>
</body>
</html>
2. display_values.php - Display Submitted Data:
<?php
// Get values from the form
$name = $_POST['name'];
$gender = $_POST['gender'];
$subjects = isset($_POST['subjects']) ? implode(", ", $_POST['subjects']) :
"None";
$grade = $_POST['grade'];
// Display the values
echo "<h2>Student Information</h2>";
echo "Name: " . $name . "<br>";
echo "Gender: " . $gender . "<br>";
echo "Subjects: " . $subjects . "<br>";
echo "Grade: " . $grade . "<br>";
?>

Output:
8. Create Website Registration Form using text box, check box, radio button, select,
submit button. And display user inserted value in new PHP page.

Here’s a simple example of a Website Registration Form with HTML and PHP. The
form uses text boxes, checkboxes, radio buttons, dropdown select, and a submit button.
After submission, the entered data will be displayed on another PHP page.

1. website_registration_form.php - The Registration Form:


<html>
<head>
<title>Website Registration Form</title>
</head>
<body>
<h2>Register for the Website</h2>
<form action="display_user_data.php" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>

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

<label for="password">Password:</label>
<input type="password" id="password" name="password"
required><br><br>

<label for="gender">Gender:</label>
<input type="radio" id="male" name="gender" value="Male" required>
Male
<input type="radio" id="female" name="gender" value="Female">
Female<br><br>

<label for="interests">Interests:</label><br>
<input type="checkbox" name="interests[]" value="Technology">
Technology<br>
<input type="checkbox" name="interests[]" value="Music"> Music<br>
<input type="checkbox" name="interests[]" value="Sports">
Sports<br><br>

<label for="country">Country:</label>
<select id="country" name="country">
<option value="USA">USA</option>
<option value="India">India</option>
<option value="UK">UK</option>
</select><br><br>

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


</form>
</body>
</html>

2. display_user_data.php - Display Submitted Data:

<?php

// Retrieve values from the form


$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password']; // In a real application, never display or
store passwords in plain text.
$gender = $_POST['gender'];
$interests = isset($_POST['interests']) ? implode(", ", $_POST['interests']) :
"None";
$country = $_POST['country'];

// Display the values


echo "<h2>User Registration Details</h2>";
echo "Username: " . htmlspecialchars($username) . "<br>";
echo "Email: " . htmlspecialchars($email) . "<br>";
echo "Password: " . htmlspecialchars($password) . "<br>";
echo "Gender: " . htmlspecialchars($gender) . "<br>";
echo "Interests: " . htmlspecialchars($interests) . "<br>";
echo "Country: " . htmlspecialchars($country) . "<br>";
?>

Output:

How It Works:

1. website_registration_form.php contains an HTML form with text fields, radio


buttons for gender, checkboxes for interests, a dropdown for country selection, and
a submit button.
2. When the user submits the form, the data is sent to display_user_data.php via the
POST method.
3. display_user_data.php retrieves the submitted values using $_POST, then it
securely displays the input using htmlspecialchars() to prevent cross-site scripting
(XSS) attacks.
9. Write PHP script to demonstrate passing variables with cookies.

Here's a simple PHP script that demonstrates how to pass variables using cookies.
This example will involve two pages: one to set the cookie, and another to retrieve
and display the cookie value.

1. set_cookie.php - Setting the Cookie:


<?php
// Set a cookie with the name "user" and value "John Doe", expires in 1 hour
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (3600), "/"); // 3600 seconds = 1
hour
?>
<!DOCTYPE html>
<html>
<head>
<title>Set Cookie</title>
</head>
<body>
<h2>Setting Cookie</h2>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value: " . $_COOKIE[$cookie_name];
}
?>
<br><br>
<a href="get_cookie.php">Go to Next Page to Get Cookie</a>
</body>
</html>
2. get_cookie.php - Retrieving the Cookie:

<?php

// Retrieve the cookie set previously


$cookie_name = "user";
?>
<!DOCTYPE html>
<html>
<head>
<title>Get Cookie</title>
</head>
<body>
<h2>Retrieving Cookie</h2>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Welcome " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>

How It Works:

1. set_cookie.php sets a cookie named "user" with the value "John Doe". The cookie
will expire in 1 hour.
2. When you visit the set_cookie.php page, it will display a message showing the
cookie has been set.
3. The link in set_cookie.php takes you to get_cookie.php, which retrieves and
displays the cookie value (i.e., "Welcome John Doe").
10.Write a program to keep track of how many times a visitor has loaded the page.

Here’s a simple PHP program that tracks how many times a visitor has loaded a
page using cookies:
<?php

// Check if the cookie 'page_visits' exists


if(isset($_COOKIE['page_visits'])) {
// Increment the value of the cookie
$visits = $_COOKIE['page_visits'] + 1;
} else {
// If the cookie doesn't exist, set it to 1 (first visit)
$visits = 1;
}
// Set the cookie with the updated value, expires in 1 day (86400 seconds)
setcookie('page_visits', $visits, time() + 86400);
?>
<html>
<head>
<title>Page Visit Counter</title>
</head>
<body>
<h2>Page Visit Counter</h2>
<?php
if($visits == 1) {
echo "Welcome! This is your first visit to this page.";
} else {
echo "You have visited this page " . $visits . " times.";
}
?>
</body>
</html>
How It Works:

1. The program checks if the page_visits cookie exists.


2. If the cookie exists, it increments the value by 1, meaning the user has visited the
page before.
3. If the cookie doesn’t exist (i.e., it's the first visit), it sets the value to 1.
4. The cookie is stored for 1 day (86400 seconds), so it will persist even after the user
closes the browser.

11.Write a PHP application to add new Rows in a Table?

Here’s a simple PHP application to add new rows to an HTML table using a form. This
example uses an array to store new rows dynamically, and upon form submission, the
new data will be added to the table.

PHP Program:

1. add_row_form.php - The main page with the form to add new rows:
<!DOCTYPE html>
<html>
<head>
<title>Add New Row to Table</title>
</head>
<body>
<h2>Add New Student Information</h2>
<form action="add_row.php" method="POST">
<label for="name">Student Name:</label>
<input type="text" id="name" name="name" required><br><br>

<label for="age">Age:</label>
<input type="number" id="age" name="age" required><br><br>

<label for="grade">Grade:</label>
<input type="text" id="grade" name="grade" required><br><br>

<input type="submit" value="Add Student">


</form>

<h2>Student Table</h2>
<?php
// Predefined array to store student details
if(isset($_SESSION['students'])) {
$students = $_SESSION['students'];
} else {
$students = [];
}
// Check if form data is available and add to the students array
if(isset($_POST['name']) && isset($_POST['age']) && isset($_POST['grade'])) {
$new_student = [
"name" => $_POST['name'],
"age" => $_POST['age'],
"grade" => $_POST['grade']
];
$students[] = $new_student;
// Store the array in session to maintain the data
$_SESSION['students'] = $students;
}
// Display the table only if there are students added
if(!empty($students)) {
echo "<table border='1'>
<tr>
<th>Name</th>
<th>Age</th>
<th>Grade</th>
</tr>";
foreach ($students as $student) {
echo "<tr>
<td>{$student['name']}</td>
<td>{$student['age']}</td>
<td>{$student['grade']}</td>
</tr>";
}
echo "</table>";
} else {
echo "No students added yet.";
}
?>
</body>
</html>
Output:
12.Write a PHP application to modify the Rows in a Table.

Here's a simple PHP application to modify rows in a table. This example uses a form to
update existing rows in an HTML table.

Steps:

1. The user can enter new information (name, age, grade).


2. Upon submission, the table will allow modifying specific rows by using a simple
form to update the data.

PHP Program:

1. modify_row_form.php - The page where rows can be modified.

<?php
session_start(); // Start session to store data across pages

// Predefined array to store student details, if session not already set


if (!isset($_SESSION['students'])) {
$_SESSION['students'] = [
["name" => "John Doe", "age" => 20, "grade" => "A"],
["name" => "Jane Smith", "age" => 22, "grade" => "B"]
];
}

// Check if form is submitted to modify student details


if (isset($_POST['index']) && isset($_POST['name']) && isset($_POST['age'])
&& isset($_POST['grade'])) {
$index = $_POST['index']; // Row index to modify
$_SESSION['students'][$index] = [
"name" => $_POST['name'],
"age" => $_POST['age'],
"grade" => $_POST['grade']
];
}
?>
<html>
<head>
<title>Modify Row in Table</title>
</head>
<body>
<h2>Modify Student Information</h2>

<?php
// Display the table with an edit button for each row
echo "<table border='1'>
<tr>
<th>Name</th>
<th>Age</th>
<th>Grade</th>
<th>Action</th>
</tr>";

foreach ($_SESSION['students'] as $index => $student) {


echo "<tr>
<td>{$student['name']}</td>
<td>{$student['age']}</td>
<td>{$student['grade']}</td>
<td>
<form action='' method='POST'>
<input type='hidden' name='index' value='{$index}'>
<input type='text' name='name' value='{$student['name']}'
required>
<input type='number' name='age' value='{$student['age']}'
required>
<input type='text' name='grade' value='{$student['grade']}'
required>
<input type='submit' value='Modify'>
</form>
</td>
</tr>";
}

echo "</table>";
?>
</body>
</html>
Output:

1. Before Modification (default data):

2. After Modification (editing "Madhav" to "Pavan"):

How It Works:

1. Session Storage: The student data is stored in the session ($_SESSION['students'])


to retain the data across page reloads.
2. Display the Table: The table shows student information (name, age, grade) and
includes an edit form for each row.
3. Modify the Row: Each row has an edit form where the user can modify the
student’s information. Upon form submission, the corresponding row in the session
is updated.
13.Write a PHP application to delete the Rows from a Table.

How to delete rows from a table. This example allows users to delete specific rows
from an HTML table by using a delete button.

PHP Program:

1. delete_row_form.php - The main page to display and delete rows.


<?php
session_start(); // Start session to store data across page reloads

// Initialize student data if session is not set


if (!isset($_SESSION['students'])) {
$_SESSION['students'] = [
["name" => "John Doe", "age" => 20, "grade" => "A"],
["name" => "Jane Smith", "age" => 22, "grade" => "B"],
["name" => "Sam Brown", "age" => 19, "grade" => "C"]
];
}

// Delete the student data when the delete button is clicked


if (isset($_POST['delete_index'])) {
$delete_index = $_POST['delete_index'];
unset($_SESSION['students'][$delete_index]);
// Reindex the array to fill the gaps after deletion
$_SESSION['students'] = array_values($_SESSION['students']);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Delete Rows from Table</title>
</head>
<body>
<h2>Student Table</h2>

<table border="1" cellpadding="10">


<tr>
<th>Name</th>
<th>Age</th>
<th>Grade</th>
<th>Action</th>
</tr>

<!-- Display table rows with a delete button for each row -->
<?php foreach ($_SESSION['students'] as $index => $student): ?>
<tr>
<td><?= htmlspecialchars($student['name']) ?></td>
<td><?= htmlspecialchars($student['age']) ?></td>
<td><?= htmlspecialchars($student['grade']) ?></td>
<td>
<form method="POST" style="display:inline;">
<input type="hidden" name="delete_index" value="<?= $index
?>">
<input type="submit" value="Delete">
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>

Output:

1. Before Deletion:
2. After Deleting "Ram":

Explanation:

• The table shows a list of students with a delete button next to each row.
• When the delete button is pressed, the row is removed from the session data.
• The table updates to reflect the remaining rows after deletion.

How It Works:

1. Session Initialization: If there's no session data for students, it initializes the


session with some default data.
2. Delete Functionality: When a row's delete button is clicked, the corresponding
index is sent via POST. The PHP script then removes that index from the session
array and reindexes the array to fill the gaps.
3. Table Display: The table displays the remaining student data after deletion.
14.Write a PHP application to fetch the Rows in a Table.

How to fetch and display rows from a table. This example uses a predefined array to
simulate fetching data from a database and displays it in an HTML table.

PHP Program:

1. fetch_rows.php - The page to display rows in a table.

<?php
// Simulate fetching data from a database
$students = [
["name" => "Madhav", "age" => 20, "grade" => "A"],
["name" => "Pavan", "age" => 22, "grade" => "B"],
["name" => "Ram", "age" => 19, "grade" => "C"]
];
?>

<!DOCTYPE html>
<html>
<head>
<title>Fetch Rows from Table</title>
</head>
<body>
<h2>Student Table</h2>

<table border="1" cellpadding="10">


<tr>
<th>Name</th>
<th>Age</th>
<th>Grade</th>
</tr>

<!-- Display table rows fetched from the array -->


<?php foreach ($students as $student): ?>
<tr>
<td><?= htmlspecialchars($student['name']) ?></td>
<td><?= htmlspecialchars($student['age']) ?></td>
<td><?= htmlspecialchars($student['grade']) ?></td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>

How It Works:

1. Data Simulation: The $students array simulates data fetched from a database.
2. Table Display: The PHP script iterates over the $students array and generates table
rows for each student.

Output:

Table Display:

Explanation:

• Data Representation: The $students array holds student data.


• HTML Table: The PHP script generates an HTML table where each row represents
a student.
• Safety: htmlspecialchars is used to prevent HTML injection by escaping special
characters.
15.Develop an PHP application to implement the following Operations

i. Registration of Users.
ii. Insert the details of the Users.
iii. Modify the Details.
iv. Transaction Maintenance.
a) No of times Logged in
b) Time Spent on each login.
c) Restrict the user for three trials only.
d) Delete the user if he spent more than 100 Hrs of transaction.

To create a PHP application that handles user registration, modification, and


transaction maintenance with restrictions, you'll need to create several components.
This example will demonstrate a simplified approach using PHP sessions and file-
based storage for simplicity.

1. Create the Registration and Login Forms

register.php - For user registration.

<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Retrieve user data from the form
$username = $_POST['username'];
$password = $_POST['password'];

// Check if user already exists


$users = json_decode(file_get_contents('users.json'), true);
if (isset($users[$username])) {
echo "User already exists!";
} else {
// Register new user
$users[$username] = [
'password' => password_hash($password, PASSWORD_DEFAULT),
'logins' => 0,
'total_time' => 0,
'trials' => 0
];
file_put_contents('users.json', json_encode($users));
echo "Registration successful!";
}
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body>
<h2>Register</h2>
<form method="POST">
<label>Username:</label>
<input type="text" name="username" required><br><br>
<label>Password:</label>
<input type="password" name="password" required><br><br>
<input type="submit" value="Register">
</form>
</body>
</html>
login.php - For user login.

<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Retrieve login data from the form
$username = $_POST['username'];
$password = $_POST['password'];

// Load users data


$users = json_decode(file_get_contents('users.json'), true);

if (isset($users[$username]) && password_verify($password,


$users[$username]['password'])) {
if ($users[$username]['trials'] >= 3) {
echo "Account locked due to too many failed attempts!";
} else {
// Update login details
$users[$username]['logins'] += 1;
$_SESSION['username'] = $username;
$_SESSION['start_time'] = time();
file_put_contents('users.json', json_encode($users));
header('Location: dashboard.php');
}
} else {
if (isset($users[$username])) {
$users[$username]['trials'] += 1;
file_put_contents('users.json', json_encode($users));
}
echo "Invalid login!";
}
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form method="POST">
<label>Username:</label>
<input type="text" name="username" required><br><br>
<label>Password:</label>
<input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
2. Create the Dashboard and Handle Transactions

dashboard.php - For user interactions and transactions.

<?php
session_start();
if (!isset($_SESSION['username'])) {
header('Location: login.php');
exit();
}

$username = $_SESSION['username'];

// Load users data


$users = json_decode(file_get_contents('users.json'), true);
$user = $users[$username];

// Check if user has spent more than 100 hours


if ($user['total_time'] >= 100 * 3600) {
echo "Your account has been deleted due to excessive usage.";
unset($users[$username]);
file_put_contents('users.json', json_encode($users));
session_destroy();
exit();
}

// Update session time spent


if (isset($_SESSION['start_time'])) {
$time_spent = time() - $_SESSION['start_time'];
$users[$username]['total_time'] += $time_spent;
file_put_contents('users.json', json_encode($users));
}

// Handle logout
if (isset($_POST['logout'])) {
session_destroy();
header('Location: login.php');
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Dashboard</title>
</head>
<body>
<h2>Welcome, <?= htmlspecialchars($username) ?></h2>
<p>Number of logins: <?= $user['logins'] ?></p>
<p>Total time spent: <?= number_format($user['total_time'] / 3600, 2) ?>
hours</p>

<form method="POST">
<input type="submit" name="logout" value="Logout">
</form>
</body>
</html>

3. Create a File for Storing User Data

You will need to create a file named users.json to store user data. Initially, this file can be
empty, and the PHP scripts will handle its content.

Explanation and Output

1. Registration (register.php): Users can register by providing a username and


password. Data is stored in users.json.
2. Login (login.php): Users log in with their credentials. If successful, they are
redirected to dashboard.php. If they exceed three failed login attempts, their account
is locked.
3. Dashboard (dashboard.php): Displays user information and manages transaction
time. If a user exceeds 100 hours of total time, their account is deleted. The user can
log out, and their time spent on the dashboard is updated.

users.json:

{"madhava123":{"password":"$2y$10$kCmhg7gwb8ZVtS9xFuizYOBsnP0.uUW7
hv2aUlfa1LH0t1B4f.vGK",
"logins":0,"total_time":0,"trials":2},
"pavan":{"password":"$2y$10$j4n5DqQ0EFvW2hlnCbgTxOWRq8B4kfFiY4qIC
Wj9BhoILdd6llpNC",
"logins":2,"total_time":55,"trials":3}}

Output:

• Registration Successful:

• Login Successful:
16.Write a PHP script to connect MySQL server from your website.

To connect to a MySQL server using PHP, you can use the mysqli extension, which
provides a straightforward way to interact with MySQL databases. Below is a
simple PHP script to connect to a MySQL server and check the connection status.

PHP Script to Connect to MySQL Server

connect.php:
<?php
// Database connection parameters
$servername = "localhost"; // or your MySQL server address
$username = "root"; // your MySQL username
$password = ""; // your MySQL password
$database = "mysql"; // the database you want to connect to

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

// Check the connection


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

// Close the connection


$conn->close();
?>

Output:
Explanation:

1. Database Connection Parameters:


o $servername: The MySQL server address (usually localhost for local
servers).
o $username: Your MySQL username.
o $password: Your MySQL password.
o $database: The name of the database you want to connect to.
2. Create a Connection:
o The new mysqli() function creates a new MySQLi object with the provided
parameters.
3. Check the Connection:
o if ($conn->connect_error): Checks if there was an error during the
connection.
o die("Connection failed: " . $conn->connect_error): Displays an error message
and terminates the script if the connection fails.
4. Output:
o If the connection is successful, "Connected successfully" is displayed.
5. Close the Connection:
o $conn->close(): Closes the connection to the MySQL server.

17.Write a program to read customer information like cust-no, cust-name, item-


purchased, and mob-no, from customer table and display all these information in
table format on output screen.

To create a PHP program that reads customer information from a MySQL database
and displays it in a table format, you'll need to perform the following steps:

1. Connect to the MySQL Database


2. Fetch Data from the customer Table
3. Display Data in HTML Table Format

Here's a simple PHP script to accomplish this:


PHP Script to Read and Display Customer Information

1. Create the Database and Table

Before running the PHP script, make sure you have a MySQL database and a
customer table with the necessary fields. You can use the following SQL commands
to create the table:

CREATE DATABASE IF NOT EXISTS my_database;

USE my_database;

CREATE TABLE IF NOT EXISTS customer (


cust_no INT AUTO_INCREMENT PRIMARY KEY,
cust_name VARCHAR(100) NOT NULL,
item_purchased VARCHAR(100),
mob_no VARCHAR(15)
);

-- Insert sample data


INSERT INTO customer (cust_name, item_purchased, mob_no) VALUES
('Alice Johnson', 'Laptop', '1234567890'),
('Bob Smith', 'Smartphone', '0987654321'),
('Carol White', 'Tablet', '1122334455');

2. PHP Script: read_customers.php:

<?php
// Database connection parameters
$servername = "localhost"; // MySQL server address
$username = "root"; // MySQL username
$password = ""; // MySQL password
$database = "mysql"; // Database name

// Create a connection
$conn = new mysqli($servername, $username, $password, $database);
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Query to fetch customer information


$sql = "SELECT cust_no, cust_name, item_purchased, mob_no FROM customer";
$result = $conn->query($sql);

// Check if there are results and display them


if ($result->num_rows > 0) {
// Start HTML table
echo "<table border='1' cellpadding='10'>";
echo "<tr><th>Customer No</th><th>Customer Name</th><th>Item
Purchased</th><th>Mobile No</th></tr>";

// Output data of each row


while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . htmlspecialchars($row['cust_no']) . "</td>";
echo "<td>" . htmlspecialchars($row['cust_name']) . "</td>";
echo "<td>" . htmlspecialchars($row['item_purchased']) . "</td>";
echo "<td>" . htmlspecialchars($row['mob_no']) . "</td>";
echo "</tr>";
}
// End HTML table
echo "</table>";
} else {
echo "0 results";
}
// Close the connection
$conn->close();
?>
<?php
// Database connection parameters
$servername = "localhost"; // or your MySQL server address
$username = "root"; // your MySQL username
$password = ""; // your MySQL password
$database = "mysql"; // the database you want to connect to

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

// Check the connection


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

// Close the connection


$conn->close();
?>

Explanation:

1. Database Connection:
o $conn = new mysqli($servername, $username, $password, $database);
creates a new connection to the MySQL database.
2. Fetch Data:
o $sql = "SELECT cust_no, cust_name, item_purchased, mob_no FROM
customer"; prepares the SQL query to fetch customer data.
o $result = $conn->query($sql); executes the query and stores the result.
3. Display Data:
o The script checks if there are any results using $result->num_rows > 0.
o It starts an HTML table and iterates over each row of the result, displaying
customer details in table rows.
4. Close Connection:
o $conn->close(); closes the database connection.

Output:

Assuming you have the sample data in your customer table, the output will look like
this:

<table border="1" cellpadding="10">


<tr>
<th>Customer No</th>
<th>Customer Name</th>
<th>Item Purchased</th>
<th>Mobile No</th>
</tr>
<tr>
<td>1</td>
<td>Alice Johnson</td>
<td>Laptop</td>
<td>1234567890</td>
</tr>
<tr>
<td>2</td>
<td>Bob Smith</td>
<td>Smartphone</td>
<td>0987654321</td>
</tr>
<tr>
<td>3</td>
<td>Carol White</td>
<td>Tablet</td>
<td>1122334455</td>
</tr>
</table>
18.Write a program to edit name of customer to “Kiran” with cust-no =1, and to delete
record with cust-no=3.

To update and delete records in a MySQL database using PHP, you can use SQL
queries to perform these operations. Here’s a simple PHP script that demonstrates how
to update the customer name to "Kiran" where cust_no = 1, and delete the record with
cust_no = 3.

PHP Script: update_and_delete.php:


<?php

// Database connection parameters


$servername = "localhost"; // MySQL server address
$username = "root"; // MySQL username
$password = ""; // MySQL password
$database = "mysql"; // Database name

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

// Check the connection


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

// Update customer name to "Kiran" where cust_no = 1


$update_sql = "UPDATE customer SET cust_name = 'Kiran' WHERE cust_no = 1";
if ($conn->query($update_sql) === TRUE) {
echo "Record updated successfully.<br>";
} else {
echo "Error updating record: " . $conn->error . "<br>";
}

// Delete record where cust_no = 3


$delete_sql = "DELETE FROM customer WHERE cust_no = 3";
if ($conn->query($delete_sql) === TRUE) {
echo "Record deleted successfully.<br>";
} else {
echo "Error deleting record: " . $conn->error . "<br>";
}

// Close the connection


$conn->close();
?>

Explanation:

1. Database Connection:
o Creates a connection to the MySQL server using the mysqli class.
2. Update Operation:
o $update_sql contains the SQL query to update the customer name to
"Kiran" where cust_no = 1.
o Executes the query using $conn->query($update_sql) and checks if the
update was successful.
3. Delete Operation:
o $delete_sql contains the SQL query to delete the record where cust_no =
3.
o Executes the query using $conn->query($delete_sql) and checks if the
deletion was successful.
4. Error Handling:
o If there’s an error in executing the SQL queries, it displays an error
message.
5. Close Connection:
o Closes the database connection using $conn->close().

Output:

Successful Update and Delete:

Notes:

• Make sure to replace localhost, root, and the my_database with your actual MySQL
server credentials and database name.
• This script assumes that the customer table already exists and has records with
cust_no = 1 and cust_no = 3. Adjust the table name and field names as needed.
19.Write a program to read employee information like emp-no, emp-name, designation
and salary from EMP table and display all this information using table format in
your website.

To read employee information from an EMP table and display it in a table format on
a website, you'll need to follow these steps:

1. Create the Database and Table


2. Write the PHP Script to Fetch and Display Data

Here’s a step-by-step example:

1. Create the Database and Table

Assuming you have a MySQL database named my_database, use the following SQL
commands to create the EMP table and insert sample data:

CREATE DATABASE IF NOT EXISTS my_database;

USE my_database;

CREATE TABLE IF NOT EXISTS EMP (


emp_no INT AUTO_INCREMENT PRIMARY KEY,
emp_name VARCHAR(100) NOT NULL,
designation VARCHAR(100),
salary DECIMAL(10, 2)
);

-- Insert sample data


INSERT INTO EMP (emp_name, designation, salary) VALUES
('John Doe', 'Software Engineer', 75000.00),
('Jane Smith', 'Project Manager', 85000.00),
('Alice Johnson', 'Data Analyst', 68000.00);

2. PHP Script: read_employees.php

This PHP script will connect to the MySQL database, fetch employee information
from the EMP table, and display it in an HTML table format.

<?php
// Database connection parameters
$servername = "localhost"; // MySQL server address
$username = "root"; // MySQL username
$password = ""; // MySQL password
$database = "my_database"; // Database name

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

// Check the connection


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

// Query to fetch employee information


$sql = "SELECT emp_no, emp_name, designation, salary FROM EMP";
$result = $conn->query($sql);

// Check if there are results and display them


if ($result->num_rows > 0) {
// Start HTML table
echo "<table border='1' cellpadding='10'>";
echo "<tr><th>Employee No</th><th>Employee
Name</th><th>Designation</th><th>Salary</th></tr>";

// Output data of each row


while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . htmlspecialchars($row['emp_no']) . "</td>";
echo "<td>" . htmlspecialchars($row['emp_name']) . "</td>";
echo "<td>" . htmlspecialchars($row['designation']) . "</td>";
echo "<td>" . htmlspecialchars($row['salary']) . "</td>";
echo "</tr>";
}

// End HTML table


echo "</table>";
} else {
echo "0 results";
}
// Close the connection
$conn->close();
?>

Explanation:

1. Database Connection:
o Creates a connection to the MySQL server using mysqli.
2. Fetch Data:
o $sql contains the SQL query to fetch employee data from the EMP table.
o Executes the query with $conn->query($sql) and stores the result.
3. Display Data:
o Checks if there are any results with $result->num_rows > 0.
o Starts an HTML table and iterates over each row of the result to display
employee details in table rows.
4. Close Connection:
o Closes the database connection using $conn->close().

Output:

Assuming the EMP table contains the sample data, the output will look like this in your
web browser:

<table border="1" cellpadding="10">


<tr>
<th>Employee No</th>
<th>Employee Name</th>
<th>Designation</th>
<th>Salary</th>
</tr>
<tr>
<td>1</td>
<td>John Doe</td>
<td>Software Engineer</td>
<td>75000.00</td>
</tr>
<tr>
<td>2</td>
<td>Jane Smith</td>
<td>Project Manager</td>
<td>85000.00</td>
</tr>
<tr>
<td>3</td>
<td>Alice Johnson</td>
<td>Data Analyst</td>
<td>68000.00</td>
</tr>
</table>
20.Create a dynamic web site using PHP and MySQL.

Creating a dynamic website using PHP and MySQL involves several steps, including
setting up a MySQL database, creating a PHP script to interact with the database, and
designing a simple web interface. Below is a step-by-step guide with simple code
examples to create a basic dynamic website where users can view, add, and delete
records.

1. Setup MySQL Database

First, create a MySQL database and a table to store data. Here’s how you can do it:

SQL Commands:

CREATE DATABASE IF NOT EXISTS my_database;

USE my_database;

CREATE TABLE IF NOT EXISTS items (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL
);

-- Insert sample data


INSERT INTO items (name) VALUES ('Item 1'), ('Item 2'), ('Item 3');

2. Create PHP Scripts

Here are the PHP scripts needed for basic operations: displaying data, adding new
data, and deleting data.

a. Database Connection: db_connect.php

Create a file named db_connect.php to manage the database connection.

<?php
// Database connection parameters
$servername = "localhost";
$username = "root";
$password = "";
$database = "my_database";
// Create a connection
$conn = new mysqli($servername, $username, $password, $database);

// Check the connection


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

b. Display Data: index.php

Create a file named index.php to display data from the database.

<?php
include 'db_connect.php'; // Include database connection

// Fetch data from the database


$sql = "SELECT * FROM items";
$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html>
<head>
<title>Dynamic Website</title>
</head>
<body>
<h1>Items List</h1>
<table border="1" cellpadding="10">
<tr>
<th>ID</th>
<th>Name</th>
<th>Actions</th>
</tr>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . htmlspecialchars($row['id']) . "</td>";
echo "<td>" . htmlspecialchars($row['name']) . "</td>";
echo "<td><a href='delete.php?id=" . $row['id'] .
"'>Delete</a></td>";
echo "</tr>";
}
} else {
echo "<tr><td colspan='3'>No records found</td></tr>";
}
?>
</table>
<h2>Add New Item</h2>
<form action="add.php" method="post">
<label for="name">Item Name:</label>
<input type="text" id="name" name="name" required>
<input type="submit" value="Add Item">
</form>
</body>
</html>

<?php
$conn->close();
?>

c. Add Data: add.php

Create a file named add.php to handle adding new items.

<?php
include 'db_connect.php'; // Include database connection
// Get data from POST request
$name = $_POST['name'];
// Insert data into the database
$sql = "INSERT INTO items (name) VALUES ('$name')";
if ($conn->query($sql) === TRUE) {
echo "New item added successfully. <a href='index.php'>Go back</a>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
d. Delete Data: delete.php

Create a file named delete.php to handle deleting items.

<?php
include 'db_connect.php'; // Include database connection

// Get ID from URL


$id = $_GET['id'];

// Delete data from the database


$sql = "DELETE FROM items WHERE id=$id";
if ($conn->query($sql) === TRUE) {
echo "Item deleted successfully. <a href='index.php'>Go back</a>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

Output:

1. index.php: Displays a list of items with options to add and delete.


2. Adding New Item: A form at the bottom of index.php allows users to add new
items.
3. Deleting Item: Each item has a delete link that removes the item from the
database.

How to Test:

1. Visit index.php: You should see a table of items with an option to add new
items and delete existing ones.
2. Add Items: Use the form to add new items to the database.
3. Delete Items: Click the delete link next to an item to remove it from the
database.

Important Notes:

• Security: For production, consider using prepared statements to prevent SQL


injection and handle user input validation.
• Database Credentials: Ensure your database credentials are secure and not exposed in
public repositories or shared environments.

You might also like