How to develop Projects(BDMS) Using PHP and Mysql
Part 9
Project Structure:
│──
/donors/
│ ├──
register.php #
Donor registration
│ ├──
edit_donor.php # Edit
donor details
│ ├──
delete_donor.php # Delete donor
details
│ ├──
donor_list.php # List all
donors
Database Table (donors)
CREATE TABLE donors (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
blood_group ENUM('A+', 'A-', 'B+', 'B-', 'O+',
'O-', 'AB+', 'AB-') NOT NULL,
contact VARCHAR(15),
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Features of register.php
- Uses
MySQLi procedural method for database operations.
- Ensures
basic validation (all fields required, email format, and unique
email check).
- Uses
hashed password storage for security.
- Inserts
data into the donors table.
register.php
<?php
session_start();
include("../config/db_connect.php");
// Include database connection file
$message = "";
if ($_SERVER["REQUEST_METHOD"]
== "POST") {
// Get form data
$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$blood_group = trim($_POST["blood_group"]);
$contact = trim($_POST["contact"]);
$password = trim($_POST["password"]);
// Validate inputs
if (empty($name) || empty($email) || empty($blood_group)
|| empty($contact) || empty($password)) {
$message = "All fields are
required!";
} elseif (!filter_var($email,
FILTER_VALIDATE_EMAIL)) {
$message = "Invalid email
format!";
} else {
// Check if email already exists
$check_email_query = "SELECT id
FROM donors WHERE email = '$email'";
$result = mysqli_query($conn, $check_email_query);
if (mysqli_num_rows($result) > 0) {
$message = "Email already
registered!";
} else {
// Hash password
$hashed_password = password_hash($password,
PASSWORD_BCRYPT);
// Insert donor data
$insert_query = "INSERT INTO
donors (name, email, blood_group, contact, password)
VALUES ('$name', '$email',
'$blood_group', '$contact', '$hashed_password')";
if (mysqli_query($conn, $insert_query))
{
$_SESSION["success"]
= "Registration successful! You can now login.";
header("Location:
login.php");
exit();
} else {
$message = "Something went
wrong. Please try again!";
}
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Donor Registration - Blood
Donation System</title>
<link rel="stylesheet" href="../assets/css/style.css">
<!-- Include CSS file -->
</head>
<body>
<div class="container">
<h2>Donor Registration</h2>
<?php
if (!empty($message)) {
echo '<div
class="error">' . $message . '</div>';
}
if (isset($_SESSION["success"]))
{
echo '<div
class="success">' . $_SESSION["success"] . '</div>';
unset($_SESSION["success"]);
}
?>
<form action="register.php"
method="POST">
<label for="name">Full
Name:</label>
<input type="text"
name="name" required>
<label for="email">Email:</label>
<input type="email"
name="email" required>
<label for="blood_group">Blood
Group:</label>
<select name="blood_group"
required>
<option value="">Select</option>
<option value="A+">A+</option>
<option value="A-">A-</option>
<option value="B+">B+</option>
<option value="B-">B-</option>
<option value="O+">O+</option>
<option value="O-">O-</option>
<option value="AB+">AB+</option>
<option value="AB-">AB-</option>
</select>
<label for="contact">Contact
Number:</label>
<input type="text"
name="contact" required pattern="[0-9]{10}" title="Enter
a valid 10-digit number">
<label for="password">Password:</label>
<input type="password"
name="password" required>
<button type="submit">Register</button>
</form>
<p>Already registered? <a
href="login.php">Login here</a></p>
</div>
</body>
</html>
Explanation of Key
Features
1.
Form Handling
o Collects
user input via $_POST and trims extra spaces.
o Validates
required fields, email format, and unique email check.
2.
Security Measures
o Uses
password_hash() to store a hashed password securely.
o Prevents
SQL injection by using mysqli_real_escape_string().
o Redirects
to login.php on successful registration.
3.
Session Messages
o Displays
errors if validation fails.
o Shows
success message if registration is completed.
Features of edit_donor.php:
- Retrieves
donor information from the database for editing using their unique id.
- Allows
updating donor information such as name, email, blood group, contact, and
password.
- Validates
inputs to ensure proper data entry.
- Updates
the donor's information in the database upon form submission.
edit_donor.php
<?php
session_start();
include("../config/db_connect.php");
// Include database connection file
// Check if donor is
logged in
if (!isset($_SESSION["donor_id"]))
{
header("Location: login.php"); //
Redirect to login if not logged in
exit();
}
// Fetch donor's current
information
$donor_id = $_SESSION["donor_id"];
$donor = null;
$query = "SELECT id,
name, email, blood_group, contact FROM donors WHERE id = '$donor_id'";
$result = mysqli_query($conn,
$query);
if (mysqli_num_rows($result)
> 0) {
$donor = mysqli_fetch_assoc($result);
} else {
$_SESSION["error"] = "Donor
not found!";
header("Location: dashboard.php");
exit();
}
$message = "";
if ($_SERVER["REQUEST_METHOD"]
== "POST") {
// Get updated form data
$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$blood_group = trim($_POST["blood_group"]);
$contact = trim($_POST["contact"]);
$password = trim($_POST["password"]);
// Validate inputs
if (empty($name) || empty($email) || empty($blood_group)
|| empty($contact)) {
$message = "All fields are
required!";
} elseif (!filter_var($email,
FILTER_VALIDATE_EMAIL)) {
$message = "Invalid email
format!";
} else {
// If password is provided, hash it,
otherwise keep the old password
if (!empty($password)) {
$hashed_password = password_hash($password,
PASSWORD_BCRYPT);
$update_query = "UPDATE donors
SET name = '$name', email = '$email', blood_group = '$blood_group', contact = '$contact',
password = '$hashed_password' WHERE id = '$donor_id'";
} else {
// Update without changing the
password
$update_query = "UPDATE donors
SET name = '$name', email = '$email', blood_group = '$blood_group', contact = '$contact'
WHERE id = '$donor_id'";
}
// Execute the update query
if (mysqli_query($conn, $update_query))
{
$_SESSION["success"] = "Profile
updated successfully!";
header("Location:
dashboard.php"); // Redirect to dashboard after successful update
exit();
} else {
$message = "Something went
wrong. Please try again!";
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Edit Donor Profile - Blood
Donation System</title>
<link rel="stylesheet" href="../assets/css/style.css">
<!-- Include CSS file -->
</head>
<body>
<div class="container">
<h2>Edit Donor Profile</h2>
<?php
if (!empty($message)) {
echo '<div
class="error">' . $message . '</div>';
}
if (isset($_SESSION["success"]))
{
echo '<div
class="success">' . $_SESSION["success"] . '</div>';
unset($_SESSION["success"]);
}
?>
<form action="edit_donor.php"
method="POST">
<label for="name">Full
Name:</label>
<input type="text"
name="name" value="<?php echo htmlspecialchars($donor['name']);
?>" required>
<label for="email">Email:</label>
<input type="email"
name="email" value="<?php echo htmlspecialchars($donor['email']);
?>" required>
<label for="blood_group">Blood
Group:</label>
<select name="blood_group"
required>
<option value="<?php
echo htmlspecialchars($donor['blood_group']); ?>"><?php echo htmlspecialchars($donor['blood_group']);
?></option>
<option value="A+">A+</option>
<option value="A-">A-</option>
<option value="B+">B+</option>
<option value="B-">B-</option>
<option value="O+">O+</option>
<option value="O-">O-</option>
<option value="AB+">AB+</option>
<option value="AB-">AB-</option>
</select>
<label for="contact">Contact
Number:</label>
<input type="text"
name="contact" value="<?php echo htmlspecialchars($donor['contact']);
?>" required pattern="[0-9]{10}" title="Enter a valid
10-digit number">
<label for="password">New
Password (Leave empty if you don't want to change it):</label>
<input type="password"
name="password">
<button
type="submit">Update Profile</button>
</form>
<p><a
href="dashboard.php">Back to Dashboard</a></p>
</div>
</body>
</html>
Explanation of Key
Features
1.
Session Validation
o Before
accessing the edit_donor.php page, it checks if the donor is logged in by
verifying the session ($_SESSION["donor_id"]). If not, the donor is
redirected to the login page.
2.
Fetching Donor Information
o The
donor's information is fetched from the database using the donor's id stored in
the session. The SELECT query retrieves the donor's details (name, email, blood_group,
and contact).
3.
Updating Donor Information
o When
the form is submitted, the system validates the inputs. If everything is valid,
it updates the donor's details.
o If
a new password is provided, it is hashed using password_hash() and saved in the
database.
o If
the password is not provided, the password remains unchanged.
o The
query executes the UPDATE statement using the donor's id to ensure the correct
record is updated.
4.
Feedback Messages
o Displays
error messages if any validation fails.
o Success
messages are shown upon successful profile update.
5.
Form Pre-population
o The
form fields are pre-populated with the donor's current details using PHP echo
and htmlspecialchars() to prevent XSS attacks.
6.
Redirects
o After
a successful update, the donor is redirected to the dashboard.php page.
Features of delete_donor.php:
- Confirms
the deletion action before proceeding.
- Deletes
the donor’s data from the donors table based on their unique id.
- Includes
security checks to ensure the logged-in donor can only delete their own
account.
delete_donor.php
<?php
session_start();
include("../config/db_connect.php");
// Include database connection file
// Check if donor is
logged in
if (!isset($_SESSION["donor_id"]))
{
header("Location: login.php"); //
Redirect to login if not logged in
exit();
}
$donor_id = $_SESSION["donor_id"];
// Check if the donor
wants to delete their account
if (isset($_GET['confirm'])
&& $_GET['confirm'] == 'yes') {
// Prepare query to delete the donor record
$delete_query = "DELETE FROM donors
WHERE id = '$donor_id'";
if (mysqli_query($conn, $delete_query)) {
// Destroy session and redirect to
login page after successful deletion
session_unset();
session_destroy();
$_SESSION["success"] = "Your
account has been deleted successfully.";
header("Location: login.php");
exit();
} else {
$_SESSION["error"] = "Error
occurred while deleting your account. Please try again.";
}
}
// Display confirmation
message before deletion
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Delete Account - Blood
Donation System</title>
<link rel="stylesheet" href="../assets/css/style.css">
<!-- Include CSS file -->
</head>
<body>
<div class="container">
<h2>Are you sure you want to delete
your account?</h2>
<?php
if (isset($_SESSION["error"]))
{
echo '<div
class="error">' . $_SESSION["error"] . '</div>';
unset($_SESSION["error"]);
}
if (isset($_SESSION["success"]))
{
echo '<div
class="success">' . $_SESSION["success"] . '</div>';
unset($_SESSION["success"]);
}
?>
<p>If you delete your account,
all your data will be permanently removed from the system. This action cannot
be undone.</p>
<a href="delete_donor.php?confirm=yes"
class="btn-danger">Yes, Delete My Account</a>
<a href="dashboard.php" class="btn-primary">No,
Go Back to Dashboard</a>
</div>
</body>
</html>
Explanation of Key
Features
1.
Session Validation
o It
checks if the donor is logged in by verifying the session ($_SESSION["donor_id"]).
If not logged in, the donor is redirected to the login.php page.
2.
Confirmation Before Deletion
o When
the donor clicks the "Yes, Delete My Account" link, it triggers the
deletion process. This is handled by checking the $_GET['confirm'] parameter in
the URL. The parameter is set to 'yes' when the donor confirms deletion.
3.
Deleting Donor Record
o The
query DELETE FROM donors WHERE id = '$donor_id' deletes the donor’s record from
the database, based on the donor's unique id.
o If
the deletion is successful, the donor is logged out by destroying the session (session_unset()
and session_destroy()), and they are redirected to the login.php page with a
success message.
o If
there is an error during deletion, an error message is shown.
4.
Redirecting After Deletion
o After
a successful deletion, the donor is redirected to the login.php page to log
out, and a success message is shown.
5.
Confirmation Page
o If
the donor has not confirmed deletion yet, a confirmation message is displayed
on the page, along with two options:
§ Yes,
Delete My Account: This link will confirm deletion.
§ No,
Go Back to Dashboard: This link will return the donor to the
dashboard without performing any action.
Features of donor_list.php:
- Displays
a list of all donors in a table.
- Provides
options for the admin to edit or delete donor records.
- Implements
pagination to handle large amounts of data efficiently.
donor_list.php Code
<?php
session_start();
include("../config/db_connect.php");
// Include database connection file
// Check if the user is
logged in and is an admin (assuming user roles are stored in the session)
if (!isset($_SESSION["admin_id"]))
{
header("Location: login.php"); //
Redirect to login if not logged in
exit();
}
// Pagination setup
$limit = 10; // Number of
donors per page
$page = isset($_GET['page'])
? (int)$_GET['page'] : 1;
$start = ($page - 1) * $limit;
// Get the total number
of donors for pagination
$total_query = "SELECT
COUNT(*) AS total FROM donors";
$total_result = mysqli_query($conn,
$total_query);
$total_row = mysqli_fetch_assoc($total_result);
$total_donors = $total_row['total'];
$total_pages = ceil($total_donors
/ $limit);
// Fetch donors for the
current page
$donor_query = "SELECT
id, name, email, blood_group, contact, created_at FROM donors LIMIT $start, $limit";
$donor_result = mysqli_query($conn,
$donor_query);
// Handle delete action
if (isset($_GET['delete_id']))
{
$donor_id = $_GET['delete_id'];
// Prepare query to delete the donor
$delete_query = "DELETE FROM donors
WHERE id = '$donor_id'";
if (mysqli_query($conn, $delete_query)) {
$_SESSION["success"] = "Donor
deleted successfully!";
} else {
$_SESSION["error"] = "Error
occurred while deleting the donor.";
}
// Redirect back to the donor list page
after deletion
header("Location: donor_list.php");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Donor List - Blood Donation
System</title>
<link rel="stylesheet" href="../assets/css/style.css">
<!-- Include CSS file -->
</head>
<body>
<div class="container">
<h2>Donor List</h2>
<?php
if (isset($_SESSION["error"]))
{
echo '<div
class="error">' . $_SESSION["error"] . '</div>';
unset($_SESSION["error"]);
}
if (isset($_SESSION["success"]))
{
echo '<div
class="success">' . $_SESSION["success"] . '</div>';
unset($_SESSION["success"]);
}
?>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Blood
Group</th>
<th>Contact</th>
<th>Joined
On</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
// Display the donor list
if (mysqli_num_rows($donor_result)
> 0) {
while ($donor = mysqli_fetch_assoc($donor_result))
{
echo "<tr>
<td>" . htmlspecialchars($donor['name']) . "</td>
<td>" . htmlspecialchars($donor['email']) . "</td>
<td>" . htmlspecialchars($donor['blood_group']) . "</td>
<td>" . htmlspecialchars($donor['contact']) . "</td>
<td>" . htmlspecialchars($donor['created_at']) . "</td>
<td>
<a
href='edit_donor.php?id=" . $donor['id'] . "'
class='btn-primary'>Edit</a>
<a
href='donor_list.php?delete_id=" . $donor['id'] . "'
class='btn-danger' onclick='return confirm(\"Are you sure you want to
delete this donor?\")'>Delete</a>
</td>
</tr>";
}
} else {
echo "<tr><td
colspan='6'>No donors found.</td></tr>";
}
?>
</tbody>
</table>
<!-- Pagination -->
<div class="pagination">
<a href="?page=1" class="btn-page">First</a>
<a href="?page=<?php echo
max($page - 1, 1); ?>" class="btn-page">Prev</a>
<span>Page <?php echo $page;
?> of <?php echo $total_pages; ?></span>
<a href="?page=<?php echo
min($page + 1, $total_pages); ?>" class="btn-page">Next</a>
<a href="?page=<?php echo
$total_pages; ?>" class="btn-page">Last</a>
</div>
</div>
</body>
</html>
Explanation of Key
Features
1.
Session Validation
o It
checks if an admin is logged in by verifying the session ($_SESSION["admin_id"]).
If the session is not set, the user is redirected to the login page.
2.
Pagination
o Pagination
is implemented to handle large lists of donors efficiently.
o The
LIMIT clause is used to fetch only a specific number of donors per page.
o The
number of pages is calculated based on the total number of donors, and links
are generated for navigation between pages.
3.
Fetching Donor Information
o The
donor information is fetched using the query:
SELECT id, name, email,
blood_group, contact, created_at FROM donors LIMIT $start, $limit;
This query retrieves
donor details for the current page, based on the page number and the limit.
4.
Delete Donor
o The
delete action is handled by the GET parameter delete_id. When the Delete
link is clicked, the donor’s id is passed as a URL parameter to confirm the
delete action.
o The
query to delete the donor is:
DELETE FROM donors WHERE
id = '$donor_id';
If the deletion is
successful, a success message is displayed, otherwise, an error message is
shown.
5.
Confirmation for Deletion
o A
JavaScript confirmation box is used to confirm the deletion of a donor.
This prevents accidental deletions by requiring the admin to confirm the
action.
6.
Displaying Donors
o Donors
are displayed in a table with the following details:
§ Name
§ Email
§ Blood
Group
§ Contact
§ Date
of Joining (created_at)
o Each
row provides two action links: Edit and Delete.
7.
Pagination Links
o Pagination
links (First, Prev, Next, Last) allow navigation through pages of donors.
o The
max() and min() functions ensure that the page number doesn't go below 1 or
exceed the total number of pages.