III BSC - V SEMSTER PHP LAB PROGRAMS
[Link] a PHP program to Display "Hello"
<?php
echo "Hello";
?>
[Link] a PHP Program to display the today's date.
<?php
echo "Today's date is: " . date("Y-m-d");
?>
[Link] a PHP program to display Fibonacci series.
<?php
// Function to generate Fibonacci series
function fibonacci($n) {
$first = 0;
$second = 1;
// Print the first two numbers
echo $first . " " . $second . " ";
// Loop to generate the next numbers in the series
for ($i = 2; $i < $n; $i++) {
$next = $first + $second;
echo $next . " ";
$first = $second;
$second = $next;
}
}
// Number of terms to display
$n = 10;
echo "Fibonacci series up to $n terms: <br>";
fibonacci($n);
?>
Fibonacci series up to 10 terms:
0 1 1 2 3 5 8 13 21 34
[Link] a PHP Program to read the employee details'.
<!DOCTYPE html>
<html>
<head>
<title>Employee Details Form</title>
</head>
<body>
<h2>Enter Employee Details</h2>
<form method="post" action="">
Name: <input type="text" name="name"><br><br>
Position: <input type="text" name="position"><br><br>
Salary: <input type="number" name="salary" step="0.01"><br><br>
<input type="submit" value="Submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form data
$name = $_POST['name'];
$position = $_POST['position'];
$salary = $_POST['salary'];
// Display the employee details
echo "<h2>Employee Details:</h2>";
echo "Name: " . $name . "<br>";
echo "Position: " . $position . "<br>";
echo "Salary: $" . number_format($salary, 2) . "<br>";
}
?>
</body>
</html>
[Link] a PHP program to prepare the student marks list'.
<!DOCTYPE html>
<html>
<head>
<title>Student Marks List</title>
</head>
<body>
<h2>Enter Student Marks</h2>
<form method="post" action="">
Student Name: <input type="text" name="name" required><br><br>
Subject 1 Marks: <input type="number" name="subject1" min="0" max="100"
required><br><br>
Subject 2 Marks: <input type="number" name="subject2" min="0" max="100"
required><br><br>
Subject 3 Marks: <input type="number" name="subject3" min="0" max="100"
required><br><br>
Subject 4 Marks: <input type="number" name="subject4" min="0" max="100"
required><br><br>
Subject 5 Marks: <input type="number" name="subject5" min="0" max="100"
required><br><br>
<input type="submit" value="Submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form data
$name = $_POST['name'];
$subject1 = $_POST['subject1'];
$subject2 = $_POST['subject2'];
$subject3 = $_POST['subject3'];
$subject4 = $_POST['subject4'];
$subject5 = $_POST['subject5'];
// Calculate total and percentage
$total = $subject1 + $subject2 + $subject3 + $subject4 + $subject5;
$percentage = ($total / 500) * 100;
// Display the marks list
echo "<h2>Student Marks List</h2>";
echo "Student Name: " . $name . "<br>";
echo "Subject 1: " . $subject1 . "<br>";
echo "Subject 2: " . $subject2 . "<br>";
echo "Subject 3: " . $subject3 . "<br>";
echo "Subject 4: " . $subject4 . "<br>";
echo "Subject 5: " . $subject5 . "<br>";
echo "Total Marks: " . $total . " / 500<br>";
echo "Percentage: " . number_format($percentage, 2) . "%<br>";
// Determine the grade
if ($percentage >= 90) {
echo "Grade: A+<br>";
} elseif ($percentage >= 80) {
echo "Grade: A<br>";
} elseif ($percentage >= 70) {
echo "Grade: B+<br>";
} elseif ($percentage >= 60) {
echo "Grade: B<br>";
} elseif ($percentage >= 50) {
echo "Grade: C<br>";
} else {
echo "Grade: Fail<br>";
}
}
?>
</body>
</html>
[Link] a PHP program to generate the multiplication of two-matrices'.
<?php
// Function to multiply two matrices
function multiplyMatrices($matrix1, $matrix2) {
$result = array();
$rowsMatrix1 = count($matrix1);
$colsMatrix1 = count($matrix1[0]);
$colsMatrix2 = count($matrix2[0]);
// Initialize the result matrix with zeros
for ($i = 0; $i < $rowsMatrix1; $i++) {
for ($j = 0; $j < $colsMatrix2; $j++) {
$result[$i][$j] = 0;
}
}
// Matrix multiplication logic
for ($i = 0; $i < $rowsMatrix1; $i++) {
for ($j = 0; $j < $colsMatrix2; $j++) {
for ($k = 0; $k < $colsMatrix1; $k++) {
$result[$i][$j] += $matrix1[$i][$k] * $matrix2[$k][$j];
}
}
}
return $result;
}
// Function to print a matrix
function printMatrix($matrix) {
foreach ($matrix as $row) {
foreach ($row as $element) {
echo $element . " ";
}
echo "<br>";
}
}
// Define two matrices
$matrix1 = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
$matrix2 = array(
array(9, 8, 7),
array(6, 5, 4),
array(3, 2, 1)
);
// Multiply the matrices
$resultMatrix = multiplyMatrices($matrix1, $matrix2);
// Display the result
echo "<h2>Matrix 1:</h2>";
printMatrix($matrix1);
echo "<h2>Matrix 2:</h2>";
printMatrix($matrix2);
echo "<h2>Result of Matrix Multiplication:</h2>";
printMatrix($resultMatrix);
?>
Matrix 1:
1 2 3
4 5 6
7 8 9
Matrix 2:
9 8 7
6 5 4
3 2 1
Result of Matrix Multiplication:
30 24 18
84 69 54
138 114 90
[Link] student registration form using text box, check box, radio button, select,
submit button. And display user inserted value in new PHP page'.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Registration Form</title>
</head>
<body>
<h2>Student Registration Form</h2>
<form action="[Link]" method="post">
<!-- Textbox for Name -->
Name: <input type="text" name="name" required><br><br>
<!-- Textbox for Email -->
Email: <input type="email" name="email" required><br><br>
<!-- Radio Buttons for Gender -->
Gender:
<input type="radio" name="gender" value="Male" required> Male
<input type="radio" name="gender" value="Female" required> Female<br><br>
<!-- Checkbox for Hobbies -->
Hobbies: <br>
<input type="checkbox" name="hobbies[]" value="Reading"> Reading<br>
<input type="checkbox" name="hobbies[]" value="Sports"> Sports<br>
<input type="checkbox" name="hobbies[]" value="Music"> Music<br><br>
<!-- Dropdown for Course -->
Course:
<select name="course" required>
<option value="">--Select Course--</option>
<option value="Computer Science">Computer Science</option>
<option value="Mathematics">Mathematics</option>
<option value="Physics">Physics</option>
<option value="Chemistry">Chemistry</option>
</select><br><br>
<!-- Submit Button -->
<input type="submit" value="Register">
</form>
</body>
</html>
[Link] (Display User Input)
php
Copy code
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Collect form data
$name = $_POST['name'];
$email = $_POST['email'];
$gender = $_POST['gender'];
$hobbies = isset($_POST['hobbies']) ? $_POST['hobbies'] : [];
$course = $_POST['course'];
// Display the form data
echo "<h2>Student Registration Details</h2>";
echo "Name: " . htmlspecialchars($name) . "<br>";
echo "Email: " . htmlspecialchars($email) . "<br>";
echo "Gender: " . htmlspecialchars($gender) . "<br>";
// Display hobbies
if (!empty($hobbies)) {
echo "Hobbies: " . implode(", ", $hobbies) . "<br>";
} else {
echo "Hobbies: None<br>";
}
echo "Course: " . htmlspecialchars($course) . "<br>";
}
?>
Student Registration Details
Name: John Doe
Email: john@[Link]
Gender: Male
Hobbies: Reading, Sports
Course: Computer Science
[Link] Website Registration Form using text box, check box' radio button' select'
submit button. And display user inserted value in new PHP page'.
[Link] (Website Registration Form)
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Website Registration Form</title>
</head>
<body>
<h2>Website Registration Form</h2>
<form action="[Link]" method="post">
<!-- Textbox for Username -->
Username: <input type="text" name="username" required><br><br>
<!-- Textbox for Email -->
Email: <input type="email" name="email" required><br><br>
<!-- Radio Buttons for Gender -->
Gender:
<input type="radio" name="gender" value="Male" required> Male
<input type="radio" name="gender" value="Female" required> Female<br><br>
<!-- Checkbox for Interests -->
Interests: <br>
<input type="checkbox" name="interests[]" value="Technology"> Technology<br>
<input type="checkbox" name="interests[]" value="Sports"> Sports<br>
<input type="checkbox" name="interests[]" value="Music"> Music<br><br>
<!-- Dropdown for Country -->
Country:
<select name="country" required>
<option value="">--Select Country--</option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="UK">UK</option>
<option value="Australia">Australia</option>
</select><br><br>
<!-- Submit Button -->
<input type="submit" value="Register">
</form>
</body>
</html>
[Link] (Display User Input)
php
Copy code
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get form data
$username = $_POST['username'];
$email = $_POST['email'];
$gender = $_POST['gender'];
$interests = isset($_POST['interests']) ? $_POST['interests'] : [];
$country = $_POST['country'];
// Display user input
echo "<h2>Registration Details</h2>";
echo "Username: " . htmlspecialchars($username) . "<br>";
echo "Email: " . htmlspecialchars($email) . "<br>";
echo "Gender: " . htmlspecialchars($gender) . "<br>";
// Display interests
if (!empty($interests)) {
echo "Interests: " . implode(", ", $interests) . "<br>";
} else {
echo "Interests: None<br>";
}
echo "Country: " . htmlspecialchars($country) . "<br>";
}
?>
The output will be:
Registration Details
Username: john_doe
Email: john@[Link]
Gender: Male
Interests: Technology, Sports
Country: USA
[Link] PHP script to demonstrate passing variables with cookies'.
Here is a PHP script that demonstrates how to pass variables using cookies.
set_cookie.php (Setting the Cookie)
php
Copy code
<?php
// Set a cookie that stores the user's name
$cookie_name = "user";
$cookie_value = "John Doe";
// Cookie expiration time: 1 hour from now
setcookie($cookie_name, $cookie_value, time() + (3600), "/");
// Inform the user that the cookie has been set
echo "Cookie named '" . $cookie_name . "' with value '" . $cookie_value . "' has
been set. <br>";
echo "Go to the <a href='get_cookie.php'>next page</a> to check the cookie value.";
?>
get_cookie.php (Retrieving the Cookie)
php
Copy code
<?php
// Check if the cookie is set
if(isset($_COOKIE["user"])) {
echo "The cookie value is: " . htmlspecialchars($_COOKIE["user"]) . "<br>";
} else {
echo "Cookie is not set!";
}
?>
[Link] a program to keep track of how many times a visitor has loaded the page'.
To keep track of how many times a visitor has loaded a page, you can use cookies in
PHP. Here's a simple program that counts the number of page loads for each visitor
by incrementing a counter stored in a cookie.
page_counter.php (Page Load Counter)
php
Copy code
<?php
// Check if the 'page_count' cookie is set
if (isset($_COOKIE['page_count'])) {
// Increment the count if the cookie is already set
$page_count = $_COOKIE['page_count'] + 1;
} else {
// If the cookie is not set, initialize the count to 1
$page_count = 1;
}
// Set the updated page count as a cookie with an expiration time of 1 hour
setcookie('page_count', $page_count, time() + 3600);
// Display the number of times the page has been loaded
if ($page_count == 1) {
echo "This is your first visit to this page!";
} else {
echo "You have loaded this page " . $page_count . " times.";
}
?>
Example Output:
First Visit:
kotlin
Copy code
This is your first visit to this page!
Subsequent Visits:
kotlin
Copy code
You have loaded this page 2 times.
You have loaded this page 3 times.
...
[Link] a php application to add new Rows in a Table.
Sure! To create a PHP application that adds new rows to a table, you need to set up
a few components:
Database: A MySQL or MariaDB database.
HTML Form: To accept user input.
PHP Script: To process the form data and insert it into the database.
Here's a basic example to illustrate how you can achieve this.
1. Database Setup
First, make sure you have a MySQL or MariaDB database. Let’s assume you have a
database called test_db and a table called users with the following schema:
sql
Copy code
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL
);
2. HTML Form
Create an HTML form to accept user input. Save this as [Link]:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add New User</title>
</head>
<body>
<h1>Add New User</h1>
<form action="add_user.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<input type="submit" value="Add User">
</form>
</body>
</html>
3. PHP Script
Create a PHP script to process the form submission and insert the data into the
database. Save this as add_user.php:
php
Copy code
<?php
// Database configuration
$servername = "localhost";
$username = "root"; // Change to your database username
$password = ""; // Change to your database password
$dbname = "test_db"; // Change to your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Check if form data is posted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get form data
$name = $_POST['name'];
$email = $_POST['email'];
// Prepare and bind
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
// Execute the statement
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $stmt->error;
}
// Close statement and connection
$stmt->close();
$conn->close();
}
?>
[Link] a PHP application to modify the Rows in a Table.
To create a PHP application that modifies rows in a table, you'll need to set up
the following:
Database: A MySQL or MariaDB database with a table.
HTML Form: To accept user input for updating records.
PHP Script: To process the form data and update the record in the database.
1. Database Setup
Assuming you have a database called test_db and a table called users with the
following schema:
sql
Copy code
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL
);
2. HTML Form for Editing
Create an HTML form to select and edit a record. Save this as edit_user.html:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Edit User</title>
</head>
<body>
<h1>Edit User</h1>
<form action="update_user.php" method="post">
<label for="id">User ID:</label>
<input type="text" id="id" name="id" required><br><br>
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Update User">
</form>
</body>
</html>
3. PHP Script for Updating Data
Create a PHP script to process the form submission and update the database record.
Save this as update_user.php:
php
Copy code
<?php
// Database configuration
$servername = "localhost";
$username = "root"; // Change to your database username
$password = ""; // Change to your database password
$dbname = "test_db"; // Change to your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Check if form data is posted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get form data
$id = $_POST['id'];
$name = $_POST['name'];
$email = $_POST['email'];
// Build update query
$updateQuery = "UPDATE users SET ";
$updateParams = [];
if (!empty($name)) {
$updateQuery .= "name = ?";
$updateParams[] = $name;
}
if (!empty($email)) {
if (!empty($name)) {
$updateQuery .= ", ";
}
$updateQuery .= "email = ?";
$updateParams[] = $email;
}
$updateQuery .= " WHERE id = ?";
$updateParams[] = $id;
// Prepare and bind
$stmt = $conn->prepare($updateQuery);
// Dynamically bind parameters
$types = str_repeat('s', count($updateParams) - 1) . 'i'; // All params are
strings except the last one (id)
$stmt->bind_param($types, ...$updateParams);
// Execute the statement
if ($stmt->execute()) {
echo "Record updated successfully";
} else {
echo "Error: " . $stmt->error;
}
// Close statement and connection
$stmt->close();
$conn->close();
}
?>
[Link] a PHP application to delete the Rows from a Table.
To create a PHP application for deleting rows from a table, you’ll need the
following components:
Database: A MySQL or MariaDB database with a table.
HTML Form: To allow the user to specify which record to delete.
PHP Script: To process the form submission and delete the record from the database.
1. Database Setup
Assuming you have a database called test_db and a table called users with the
following schema:
sql
Copy code
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL
);
2. HTML Form for Deleting Records
Create an HTML form to allow the user to specify the ID of the record they want to
delete. Save this as delete_user.html:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Delete User</title>
</head>
<body>
<h1>Delete User</h1>
<form action="delete_user.php" method="post">
<label for="id">User ID:</label>
<input type="text" id="id" name="id" required><br><br>
<input type="submit" value="Delete User">
</form>
</body>
</html>
3. PHP Script for Deleting Data
Create a PHP script to process the form submission and delete the specified record
from the database. Save this as delete_user.php:
php
Copy code
<?php
// Database configuration
$servername = "localhost";
$username = "root"; // Change to your database username
$password = ""; // Change to your database password
$dbname = "test_db"; // Change to your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Check if form data is posted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get form data
$id = $_POST['id'];
// Prepare and bind
$stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
// Execute the statement
if ($stmt->execute()) {
if ($stmt->affected_rows > 0) {
echo "Record deleted successfully";
} else {
echo "No record found with ID: $id";
}
} else {
echo "Error: " . $stmt->error;
}
// Close statement and connection
$stmt->close();
$conn->close();
}
?>
[Link] a PHP application to fetch the Rows in a Table.
To create a PHP application that fetches and displays rows from a table, you'll
need the following components:
Database: A MySQL or MariaDB database with a table.
PHP Script: To query the database and fetch the data.
HTML: To display the fetched data in a readable format.
1. Database Setup
Assuming you have a database called test_db and a table called users with the
following schema:
sql
Copy code
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL
);
2. PHP Script for Fetching and Displaying Data
Create a PHP script to connect to the database, fetch data from the users table,
and display it. Save this as fetch_users.php:
php
Copy code
<?php
// Database configuration
$servername = "localhost";
$username = "root"; // Change to your database username
$password = ""; // Change to your database password
$dbname = "test_db"; // Change to your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to fetch all records from the users table
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
// Check if records are found
if ($result->num_rows > 0) {
// Output data for each row
echo "<h1>Users List</h1>";
echo "<table border='1'>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . htmlspecialchars($row["id"]) . "</td>";
echo "<td>" . htmlspecialchars($row["name"]) . "</td>";
echo "<td>" . htmlspecialchars($row["email"]) . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
// Close connection
$conn->close();
?>
[Link] and PHP application to implement the following Operations.
To develop a PHP application that performs a series of operations on a database,
you'll typically need to handle multiple functionalities such as adding, updating,
deleting, and fetching records. Here’s a basic example that covers these operations
using a users table in a MySQL database:
1. Database Setup
First, create a MySQL database and a table named users:
sql
Copy code
CREATE DATABASE test_db;
USE test_db;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL
);
2. HTML Form and PHP Scripts
[Link]: A single HTML file with links to perform different operations.
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Operations</title>
</head>
<body>
<h1>User Operations</h1>
<ul>
<li><a href="add_user.html">Add User</a></li>
<li><a href="edit_user.html">Edit User</a></li>
<li><a href="delete_user.html">Delete User</a></li>
<li><a href="fetch_users.php">Fetch Users</a></li>
</ul>
</body>
</html>
add_user.html: Form for adding a new user.
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add User</title>
</head>
<body>
<h1>Add New User</h1>
<form action="add_user.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<input type="submit" value="Add User">
</form>
</body>
</html>
edit_user.html: Form for editing an existing user.
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Edit User</title>
</head>
<body>
<h1>Edit User</h1>
<form action="update_user.php" method="post">
<label for="id">User ID:</label>
<input type="text" id="id" name="id" required><br><br>
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Update User">
</form>
</body>
</html>
delete_user.html: Form for deleting a user.
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Delete User</title>
</head>
<body>
<h1>Delete User</h1>
<form action="delete_user.php" method="post">
<label for="id">User ID:</label>
<input type="text" id="id" name="id" required><br><br>
<input type="submit" value="Delete User">
</form>
</body>
</html>
PHP Scripts
add_user.php: Handles adding a new user.
php
Copy code
<?php
// Database configuration
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get form data
$name = $_POST['name'];
$email = $_POST['email'];
// Prepare and bind
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
// Execute the statement
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $stmt->error;
}
// Close connection
$stmt->close();
$conn->close();
?>
update_user.php: Handles updating an existing user.
php
Copy code
<?php
// Database configuration
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get form data
$id = $_POST['id'];
$name = $_POST['name'];
$email = $_POST['email'];
// Build update query
$updateQuery = "UPDATE users SET ";
$updateParams = [];
if (!empty($name)) {
$updateQuery .= "name = ?";
$updateParams[] = $name;
}
if (!empty($email)) {
if (!empty($name)) {
$updateQuery .= ", ";
}
$updateQuery .= "email = ?";
$updateParams[] = $email;
}
$updateQuery .= " WHERE id = ?";
$updateParams[] = $id;
// Prepare and bind
$stmt = $conn->prepare($updateQuery);
$types = str_repeat('s', count($updateParams) - 1) . 'i'; // All params are strings
except the last one (id)
$stmt->bind_param($types, ...$updateParams);
// Execute the statement
if ($stmt->execute()) {
echo "Record updated successfully";
} else {
echo "Error: " . $stmt->error;
}
// Close connection
$stmt->close();
$conn->close();
?>
delete_user.php: Handles deleting a user.
php
Copy code
<?php
// Database configuration
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get form data
$id = $_POST['id'];
// Prepare and bind
$stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
// Execute the statement
if ($stmt->execute()) {
if ($stmt->affected_rows > 0) {
echo "Record deleted successfully";
} else {
echo "No record found with ID: $id";
}
} else {
echo "Error: " . $stmt->error;
}
// Close connection
$stmt->close();
$conn->close();
?>
fetch_users.php: Fetches and displays all users.
php
Copy code
<?php
// Database configuration
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to fetch all records from the users table
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
// Check if records are found
if ($result->num_rows > 0) {
// Output data for each row
echo "<h1>Users List</h1>";
echo "<table border='1'>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . htmlspecialchars($row["id"]) . "</td>";
echo "<td>" . htmlspecialchars($row["name"]) . "</td>";
echo "<td>" . htmlspecialchars($row["email"]) . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
// Close connection
$conn->close();
?>
Running the Application
Place Files: Ensure all files are placed in the same directory on your server.
Access Forms and Scripts: Open [Link] in your web browser to access the links
for different operations. Click on the relevant link to perform the operation you
want.