Php&mysql-Lab Manual
Php&mysql-Lab Manual
LAB-PROGRAMS
<?php
// Display the text "Hello"
echo "Hello";
?>
Output: Hello
<?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.
The Fibonacci series is a sequence of numbers where each number is the sum of the
two numbers before it.
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>";
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.
<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>
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.
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.
<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>
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.
<?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;
}
Here's a simple PHP program for creating a student registration form and displaying
the submitted values on another page:
<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>
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.
<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>
<?php
Output:
How It Works:
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.
<?php
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
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>
<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:
PHP Program:
<?php
session_start(); // Start session to store data across pages
<?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>";
echo "</table>";
?>
</body>
</html>
Output:
How It Works:
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:
<!-- 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:
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:
<?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>
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:
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.
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Retrieve user data from the form
$username = $_POST['username'];
$password = $_POST['password'];
<!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'];
<!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
<?php
session_start();
if (!isset($_SESSION['username'])) {
header('Location: login.php');
exit();
}
$username = $_SESSION['username'];
// 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>
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.
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.
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);
Output:
Explanation:
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:
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:
USE my_database;
<?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);
}
// Create a connection
$conn = new mysqli($servername, $username, $password, $database);
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:
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.
// Create a connection
$conn = new mysqli($servername, $username, $password, $database);
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:
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:
Assuming you have a MySQL database named my_database, use the following SQL
commands to create the EMP table and insert sample data:
USE my_database;
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);
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:
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.
First, create a MySQL database and a table to store data. Here’s how you can do it:
SQL Commands:
USE my_database;
Here are the PHP scripts needed for basic operations: displaying data, adding new
data, and deleting data.
<?php
// Database connection parameters
$servername = "localhost";
$username = "root";
$password = "";
$database = "my_database";
// Create a connection
$conn = new mysqli($servername, $username, $password, $database);
<?php
include 'db_connect.php'; // Include database connection
<!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();
?>
<?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
<?php
include 'db_connect.php'; // Include database connection
$conn->close();
?>
Output:
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: