Student
Registration With All types of Input
fields Using AJAX
Here are the step-by-step
instructions for beginners to login and dashboard panel ,project
with PHP, MySQL, and Bootstrap. This tutorial will guide you from the very
start, assuming you're working with a local development environment (e.g., XAMPP
or MAMP).
1. Set Up the Development Environment
To start, you need a
local server that supports PHP and MySQL. Follow these steps:
- Install
XAMPP/WAMP/MAMP (depending on your OS):
- XAMPP:
Download XAMPP
- WAMP:
Download WAMP
- MAMP:
Download MAMP
- Start
Apache and MySQL: Open the XAMPP or WAMP control
panel and start both Apache (web server) and MySQL (database server).
2. Create the Project Folder
- In
your XAMPP/WAMP/MAMP folder, locate the htdocs folder
(for XAMPP) or www folder (for WAMP/MAMP).
- Create
a new folder for your project, e.g., student_registration.
3. Set Up the Database
1. Open
phpMyAdmin:
o Go
to http://localhost/phpmyadmin/ in your web browser.
o Log
in (default username: root, no password).
2. Create
a Database:
o In
phpMyAdmin, create a new database named student_reg.
3. Create
the Users Table:
o Click
on your newly created database (student_reg).
Example SQL query to create the table:
|
4. Insert
a User for Testing:
o Go
to the SQL tab in phpMyAdmin and run this SQL command to
insert a test user:
INSERT INTO users (name,
email, password,….)
VALUES ('John Doe',
'john@example.com', MD5('password123'),….);
5. Create PHP Files for the Project
Step 1: Create the
db_connection.php File:
o This
file will handle the connection to your MySQL database.
<?php $servername =
"localhost"; $username =
"root"; // default username for MySQL in XAMPP $password =
""; // default password for MySQL in XAMPP $dbname =
"student_reg"; // Create connection $conn = new
mysqli($servername, $username, $password, $dbname); // Check connection if
($conn->connect_error) { die("Connection
failed: " . $conn->connect_error); } ?> |
Step 2:Create add_user.php
After creating the
db_connection.php file, you should create add_user.php first,
not login.php.
Reasoning:
1. Adding
Users First: You need a way to add users to your database before you can
log them in. If you create the login page (login.php) first, there will be no
users to log in unless you manually insert them into the database. The
add_user.php page will allow you to register a user (like an admin or a test
user) so you can then log in.
2. Login
After Adding Users: Once you have users added to the database using
add_user.php, you can then proceed with login.php to authenticate them.
Step-by-Step Guide for Creating add_user.php
This page will allow you
to create a user (e.g., for testing or as an admin).
1. Create
add_user.php to register users:
<!DOCTYPE html> <html
lang="en"> <head> <meta
charset="UTF-8"> <meta
name="viewport" content="width=device-width,
initial-scale=1.0"> <title>Registration
Form</title> <link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css"
rel="stylesheet"> <script
src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <style> body { background-color:
#f8f9fa; font-family: 'Arial',
sans-serif; } .form-container { background-color:
white; padding: 30px; border-radius: 8px; box-shadow: 0px 4px 8px
rgba(0, 0, 0, 0.1); max-width: 600px; margin: auto; margin-top: 50px; } h2 { text-align: center; margin-bottom: 20px; } .form-control { border-radius: 0.5rem; } .btn-primary { width: 100%; padding: 10px; border-radius: 0.5rem; } .form-group { margin-bottom: 20px; } label { font-weight: bold; } </style> </head> <body> <div
class="form-container"> <h2>Registration
Form</h2> <form
id="registrationForm" enctype="multipart/form-data"> <!-- Name --> <div
class="form-group"> <label
for="name">Name</label> <input
type="text" class="form-control" id="name"
name="name" required> </div> <!-- Email --> <div
class="form-group"> <label
for="email">Email</label> <input
type="email" class="form-control" id="email"
name="email" required> </div> <!-- Password --> <div
class="form-group"> <label
for="password">Password</label> <input
type="password" class="form-control"
id="password" name="password" required> </div> <!-- Date of Birth
--> <div
class="form-group"> <label
for="dob">Date of Birth</label> <input
type="date" class="form-control" id="dob"
name="dob" required> </div> <!-- Gender --> <div
class="form-group"> <label>Gender</label><br> <div
class="form-check form-check-inline"> <input
type="radio" class="form-check-input" id="male"
name="gender" value="Male" required> <label
class="form-check-label" for="male">Male</label> </div> <div
class="form-check form-check-inline"> <input
type="radio" class="form-check-input"
id="female" name="gender" value="Female"
required> <label
class="form-check-label"
for="female">Female</label> </div> <div
class="form-check form-check-inline"> <input
type="radio" class="form-check-input"
id="other" name="gender" value="Other"
required> <label
class="form-check-label"
for="other">Other</label> </div> </div> <!-- Course --> <div
class="form-group"> <label
for="course">Course</label> <select
id="course" class="form-control"
name="course_id" required> <option
value="">Select Course</option> </select> </div> <!-- Semester --> <div
class="form-group"> <label
for="semester">Semester</label> <select
id="semester" class="form-control"
name="semester_id" required> <option
value="">Select Semester</option> </select> </div> <!-- Section --> <div
class="form-group"> <label
for="section">Section</label> <select
id="section" class="form-control"
name="section_id" required> <option
value="">Select Section</option> </select> </div> <!-- Skills --> <div
class="form-group"> <label
for="skills">Skills</label><br> <div
class="form-check form-check-inline"> <input
type="checkbox" class="form-check-input"
name="skills[]" value="HTML"> <label
class="form-check-label" for="html">HTML</label> </div> <div
class="form-check form-check-inline"> <input
type="checkbox" class="form-check-input"
name="skills[]" value="CSS"> <label
class="form-check-label" for="css">CSS</label> </div> <div
class="form-check form-check-inline"> <input
type="checkbox" class="form-check-input"
name="skills[]" value="JavaScript"> <label
class="form-check-label"
for="js">JavaScript</label> </div> </div> <!-- Image Upload
--> <div
class="form-group"> <label
for="image">Upload Image</label> <input
type="file" class="form-control" id="image"
name="image" accept="image/*" required> </div> <!-- Submit Button
--> <button
type="submit" class="btn
btn-primary">Register</button> </form> </div> <script> $(document).ready(function()
{ // Load courses
dynamically $.ajax({ url:
'fetch_courses.php', method: 'GET', success: function(data)
{ $('#course').html(data); } }); // Load semesters based
on selected course $('#course').change(function()
{ const courseId =
$(this).val(); if (courseId) { $.ajax({ url:
'fetch_semesters.php', method: 'GET', data: { course_id:
courseId }, success: function(data)
{ $('#semester').html(data); $('#section').html('<option
value="">Select Section</option>'); } }); } else { $('#semester').html('<option
value="">Select Semester</option>'); $('#section').html('<option
value="">Select Section</option>'); } }); // Load sections based
on selected semester $('#semester').change(function()
{ const semesterId =
$(this).val(); if (semesterId) { $.ajax({ url:
'fetch_sections.php', method: 'GET', data: { semester_id:
semesterId }, success: function(data)
{ $('#section').html(data); } }); } else { $('#section').html('<option
value="">Select Section</option>'); } }); // Handle form
submission $('#registrationForm').submit(function(e)
{ e.preventDefault(); const formData = new
FormData(this); $.ajax({ url:
'save_registration.php', method: 'POST', data: formData, contentType: false, processData: false, success:
function(response) { alert(response); $('#registrationForm')[0].reset();
// Reset the form after successful submission }, error: function() { alert('Error occurred
while submitting the form.'); } }); }); }); </script> </body> </html>
|
save_registration.php
<?php require
'db_connection.php'; // Get form data $name = $_POST['name']; $email =
$_POST['email']; $password =
password_hash($_POST['password'], PASSWORD_DEFAULT); $dob = $_POST['dob']; $gender =
$_POST['gender']; $course_id =
$_POST['course_id']; $semester_id =
$_POST['semester_id']; $section_id =
$_POST['section_id']; $skills = implode(', ',
$_POST['skills']); // Convert array to comma-separated string // Handle image upload $image =
$_FILES['image']; // Define upload
directory $uploadDir =
'uploads/'; // Check if the
'uploads' directory exists, if not, create it if
(!is_dir($uploadDir)) { if
(!mkdir($uploadDir, 0777, true)) {
die("Failed to create upload directory."); } } // Define the image
path (path where image will be saved) $imagePath = $uploadDir
. basename($image['name']); // Move the uploaded
image to the 'uploads' folder if
(!move_uploaded_file($image['tmp_name'], $imagePath)) {
die("Failed to upload image."); } // Insert data into the
database $query = "INSERT
INTO users (name, email, password, dob, gender, course_id, semester_id,
section_id, skills, image_path)
VALUES ('$name', '$email', '$password', '$dob', '$gender',
$course_id, $semester_id, $section_id, '$skills', '$imagePath')"; if
($conn->query($query) === TRUE) { echo
"Registration successful!"; } else { echo
"Error: " . $conn->error; } ?> |
Things to Check:
1. Database
Table Setup:
o You
must ensure that the database table (users) has the appropriate columns for
storing the user's information, including:
§ name, email,
password, dob, gender, course_id, semester_id, section_id, skills, and image.
2. Image
Folder:
o Make
sure the uploads/ directory exists and has the proper permissions for file
uploads.
3. Form
Validation:
o The
form has client-side validation using the required attribute for the fields.
However, you should also perform server-side validation to ensure the data is
correct before inserting it into the database.
fetch_course.php
<?php require 'db_connection.php'; $query = "SELECT
id, name FROM courses"; $result =
$conn->query($query); if
($result->num_rows > 0) { echo
'<option value="">Select Course</option>'; while
($row = $result->fetch_assoc()) {
echo "<option
value='{$row['id']}'>{$row['name']}</option>"; } } else { echo
'<option value="">No Courses Available</option>'; } ?> |
Fetch_semesters.php
<?php require 'db_connection.php'; $course_id =
$_GET['course_id']; $query = "SELECT
id, name FROM semesters WHERE course_id = $course_id"; $result = $conn->query($query); if
($result->num_rows > 0) { echo
'<option value="">Select Semester</option>'; while
($row = $result->fetch_assoc()) {
echo "<option
value='{$row['id']}'>{$row['name']}</option>"; } } else { echo
'<option value="">No Semesters Available</option>'; } ?> |
fetch_section.php
<?php require
'db_connection.php'; $semester_id = $_GET['semester_id']; $query = "SELECT
id, name FROM sections WHERE semester_id = $semester_id"; $result = $conn->query($query); if
($result->num_rows > 0) { echo
'<option value="">Select Section</option>'; while
($row = $result->fetch_assoc()) {
echo "<option
value='{$row['id']}'>{$row['name']}</option>"; } } else { echo
'<option value="">No Sections Available</option>'; } ?> |
Your add_user.php script
creates a registration form with various fields such as name, email, password,
date of birth, gender, course, semester, section, skills, and image upload. The
form is submitted via AJAX, sending the data to save_registration.php for
processing and storing the data in the database.
screenshot:
Flow Of Form :
Here's how this page
works:
1. Form Structure:
The form contains the
following elements:
- Personal
Info: name, email, password, dob, gender.
- Course
and Semester Info: Dynamic select options that
are populated by AJAX requests for courses, semesters, and sections.
- Skills:
Multiple checkboxes for the user to select skills (HTML, CSS, JavaScript).
- Image
Upload: A file input for uploading an
image.
2. AJAX Calls:
- Fetching
Courses: The courses are loaded into the
course dropdown by an AJAX request to fetch_courses.php.
- Fetching
Semesters: When a course is selected, an AJAX
request to fetch_semesters.php is made to populate the semesters dropdown
based on the selected course.
- Fetching
Sections: Similarly, when a semester is
selected, an AJAX request to fetch_sections.php is made to load the
available sections for that semester.
3. Form Submission:
- When
the form is submitted, it triggers an AJAX request to
save_registration.php using POST method, sending all form data, including
the file, via FormData.
- After
submission, the form is reset, and a success or error message is displayed
based on the response.
Things to Ensure:
- fetch_courses.php:
This file should return a list of courses in the form of <option>
elements for the course dropdown.
- fetch_semesters.php:
This file should return a list of semesters based on the selected course
in the form of <option> elements for the semester dropdown.
- fetch_sections.php:
This file should return a list of sections based on the selected semester
in the form of <option> elements for the section dropdown.
- save_registration.php:
This file should handle the actual saving of user data to the database,
including validating and processing the image upload.
Testing add_user.php:
1. Open
the Form:
Navigate to http://localhost/your_project_folder/add_user.php in your browser
to load the registration form.
2. Fill
Out the Form:
o Enter
a name (e.g., John Doe).
o Enter
an email address (e.g., john.doe@example.com).
o Enter
a password (e.g., password123).
o Select
a course from the dropdown (if available).
o Choose
a semester and section (if available).
o Upload
an image (optional) by clicking the "Choose File" button.
3. Submit
the Form:
Click the Register button to submit the form. This triggers an
AJAX request, which sends the form data to the backend (save_registration.php).
4. Check
for Response:
o Upon
successful submission, you should see a success message (e.g., "User
successfully registered!").
o If
there’s an error, an error message will be displayed.
5. Verify
Data in Database:
o Open
your database (e.g., using phpMyAdmin).
o Go
to the users table and confirm that a new record has been added with the name,
email, password (hashed), and other details you provided.
o Check
if the associated course, semester, and section (if applicable) are correctly
saved in the corresponding tables.
6. Check
Image Upload (Optional):
o If
you uploaded an image, verify that it has been saved in the correct directory
(e.g., /uploads/).
o Ensure
the image path is correctly stored in the database (if relevant).
7. Check
for Errors:
o PHP
Errors: If there are any issues with the form processing, enable error
reporting in PHP by adding the following to your PHP scripts:
error_reporting(E_ALL);
ini_set('display_errors',
1);
o JavaScript
Errors: Open your browser's Developer Tools (F12 or Ctrl+Shift+I), go to
the Console tab, and check for any JavaScript errors that may
have occurred during the form submission.
8. Test
with Different Data:
Test with different user data (e.g., different emails, passwords, and image
files) to ensure that the form handles various inputs correctly.
Next Step: Create login.php
After you've created at
least one user (using add_user.php), you can then create the login.php page.
This page will authenticate users by comparing the entered password with the
one stored in the database.
login.php
<?php session_start(); require 'db_connection.php'; if
($_SERVER["REQUEST_METHOD"] == "POST") { $email =
$_POST['email']; $password = $_POST['password']; // Check
if user exists $query =
"SELECT * FROM users WHERE email = '$email'"; $result =
$conn->query($query); if
($result->num_rows > 0) { $user = $result->fetch_assoc();
// Verify password
if (password_verify($password, $user['password'])) {
// Start session and set session variables
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_name'] = $user['name'];
header("Location: dashboard.php"); //
Redirect to index page
} else {
$error = "Incorrect password!";
} } else {
$error = "User not found!"; } } ?> <!DOCTYPE html> <html
lang="en"> <head> <meta
charset="UTF-8"> <meta
name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Login</title> <!--
Bootstrap CSS --> <link
href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/css/bootstrap.min.css"
rel="stylesheet">
<style>
body {
background-color: #f4f7f6;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana,
sans-serif;
}
.login-container {
max-width: 400px;
margin: 50px auto;
padding: 30px;
background-color: white;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
border-radius: 10px;
}
.login-container h2 {
text-align: center;
margin-bottom: 20px;
}
.btn-primary {
background-color: #007bff;
border: none;
width: 100%;
padding: 12px;
font-size: 16px;
}
.btn-primary:hover {
background-color: #0056b3;
}
.form-group label {
font-weight: 600;
}
.alert {
font-size: 14px;
text-align: center;
margin-top: 20px;
}
.footer-text {
text-align: center;
font-size: 14px;
margin-top: 20px;
color: #888;
}
</style> </head> <body> <div
class="container"> <div
class="login-container"> <h2>Login</h2>
<!-- Display error message -->
<?php if (isset($error)): ?>
<div class="alert alert-danger"><?php
echo $error; ?></div> <?php endif; ?>
<form action="login.php" method="POST">
<div class="form-group">
<label
for="email">Email</label>
<input type="email"
class="form-control" id="email" name="email"
required placeholder="Enter your email">
</div>
<div class="form-group">
<label
for="password">Password</label>
<input type="password"
class="form-control" id="password"
name="password" required placeholder="Enter your
password">
</div>
<button type="submit" class="btn
btn-primary">Login</button> </form>
<div class="footer-text">
<p>Don't have an account? <a
href="add_user.php" class="text-primary">Register
here</a></p>
</div>
</div> </div> <!-- Bootstrap JS
and dependencies --> <script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script
src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.bundle.min.js"></script> </body> </html> |
Screenshot:
dashboard.php
<?php session_start(); // Check if the user is
logged in, if not, redirect to login page if
(!isset($_SESSION['user_id'])) {
header("Location: login.php"); exit(); } $user_id = $_SESSION['user_id']; $user_name =
$_SESSION['user_name']; ?> <!DOCTYPE html> <html
lang="en"> <head> <meta
charset="UTF-8"> <meta
name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Dashboard</title> <link
href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/css/bootstrap.min.css"
rel="stylesheet">
<style>
body {
background-color: #f0f8ff;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana,
sans-serif;
}
.dashboard-container {
background-color: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
text-align: center;
margin-top: 50px;
}
.dashboard-container h2 {
font-size: 2rem;
color: #007bff;
margin-bottom: 20px;
}
.dashboard-container p {
font-size: 1.2rem;
color: #555;
margin-bottom: 30px;
}
.btn-danger {
background-color: #dc3545;
border: none;
padding: 12px 25px;
font-size: 16px;
border-radius: 5px;
transition: background-color 0.3s ease;
}
.btn-danger:hover {
background-color: #c82333;
color: white;
}
.footer {
text-align: center;
font-size: 14px;
color: #888;
margin-top: 40px;
}
</style> </head> <body> <div class="container"> <div
class="dashboard-container">
<h2>Welcome, <?php echo $user_name; ?>!</h2>
<p>This is your dashboard where you can manage your settings,
view reports, and more.</p> <!-- Add any additional dashboard features here -->
<a href="logout.php" class="btn
btn-danger">Logout</a>
</div> <div
class="footer">
<p>© 2024 Your Company. All Rights Reserved.</p>
</div> </div> <!-- Bootstrap JS
and dependencies --> <script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script
src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.bundle.min.js"></script> </body> </html> |
screenshot:
logout.php
<?php session_start(); // Destroy the session session_destroy(); // Redirect to login page header("Location:
login.php"); exit(); ?> |
index.php(this is the landing page of project)
<?php // Include database
connection include 'db_connection.php'; // Fetch all users from
the database $sql = "SELECT
users.id, users.name, users.email, users.dob, users.gender,
courses.name AS course_name, semesters.name
AS semester_name,
sections.name AS section_name
FROM users
JOIN courses ON users.course_id = courses.id
JOIN semesters ON users.semester_id = semesters.id
JOIN sections ON users.section_id = sections.id"; $result =
$conn->query($sql); ?> <!DOCTYPE html> <html
lang="en"> <head> <meta
charset="UTF-8"> <meta
name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Users Management</title> <link
href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/css/bootstrap.min.css"
rel="stylesheet"> </head> <body> <div
class="container mt-4">
<h2>Users Management</h2> <!--
Add New User Button --> <a
href="add_user.php" class="btn btn-primary mb-4">Add
New User</a> <!--
Login Button --> <a
href="login.php" class="btn btn-success
mb-4">Login</a> <!--
Users Table --> <table
class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Email</th>
<th>Date of Birth</th>
<th>Gender</th>
<th>Course</th>
<th>Semester</th>
<th>Section</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php if ($result->num_rows > 0): ?>
<?php while ($row =
$result->fetch_assoc()): ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['email']; ?></td>
<td><?php echo $row['dob']; ?></td>
<td><?php echo $row['gender']; ?></td>
<td><?php echo $row['course_name']; ?></td>
<td><?php echo $row['semester_name']; ?></td>
<td><?php echo $row['section_name']; ?></td>
<td>
<a href="view_user.php?id=<?php echo $row['id']; ?>"
class="btn btn-info btn-sm">View</a>
<a href="edit_user.php?id=<?php echo $row['id']; ?>"
class="btn btn-warning btn-sm">Edit</a>
<a href="delete_user.php?id=<?php echo $row['id']; ?>"
class="btn btn-danger btn-sm" onclick="return confirm('Are you
sure you want to delete this user?');">Delete</a>
</td>
</tr>
<?php endwhile; ?>
<?php else: ?>
<tr>
<td colspan="9"
class="text-center">No users found.</td>
</tr>
<?php endif; ?>
</tbody>
</table> </div> <!-- Bootstrap JS
and dependencies --> <script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script
src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.bundle.min.js"></script> </body> </html> <?php // Close the database
connection $conn->close(); ?> |
Screenshot:
view_user.php
<?php // Include the database
connection require 'db_connection.php'; // Check if the user ID
is passed in the URL if (isset($_GET['id']))
{ $user_id
= $_GET['id']; // Fetch user data along with the course, semester, and section details $sql =
"SELECT users.id, users.name, users.email, users.dob, users.gender,
users.skills,
users.image_path, courses.name AS course_name,
semesters.name AS
semester_name, sections.name AS section_name
FROM users
JOIN courses ON users.course_id = courses.id
JOIN semesters ON users.semester_id = semesters.id
JOIN sections ON users.section_id = sections.id
WHERE users.id = ?"; // Prepare the statement if ($stmt
= $conn->prepare($sql)) {
// Bind the user ID parameter
$stmt->bind_param('i', $user_id);
// Execute the query
$stmt->execute(); // Get the result
$result = $stmt->get_result(); if ($result->num_rows > 0) {
// Fetch the user data
$user = $result->fetch_assoc();
} else {
// If no user found, redirect to index.php
header("Location: index.php");
exit();
} // Close the statement
$stmt->close(); } else {
// If there is an issue with the query, redirect to index.php
header("Location: index.php");
exit(); } } else { // If the
user ID is not set, redirect to index.php
header("Location: index.php"); exit(); } // Close the database connection $conn->close(); ?> <!DOCTYPE html> <html
lang="en"> <head> <meta
charset="UTF-8"> <meta
name="viewport" content="width=device-width,
initial-scale=1.0">
<title>User Details</title> <link
href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/css/bootstrap.min.css"
rel="stylesheet"> </head> <body> <div class="container mt-4">
<h2>User Details</h2> <!-- Display the user details --> <div
class="card">
<div class="card-body">
<h5 class="card-title"><?php echo
htmlspecialchars($user['name']); ?></h5>
<p
class="card-text"><strong>Email:</strong> <?php
echo htmlspecialchars($user['email']); ?></p>
<p class="card-text"><strong>Date
of Birth:</strong> <?php echo htmlspecialchars($user['dob']);
?></p>
<p
class="card-text"><strong>Gender:</strong> <?php
echo htmlspecialchars($user['gender']); ?></p>
<p
class="card-text"><strong>Course:</strong> <?php
echo htmlspecialchars($user['course_name']); ?></p>
<p
class="card-text"><strong>Semester:</strong>
<?php echo htmlspecialchars($user['semester_name']); ?></p>
<p
class="card-text"><strong>Section:</strong> <?php
echo htmlspecialchars($user['section_name']); ?></p>
<p
class="card-text"><strong>Skills:</strong> <?php
echo htmlspecialchars($user['skills']); ?></p>
<!-- Display the image if exists -->
<?php if (!empty($user['image_path'])): ?>
<p><strong>Profile
Image:</strong></p>
<img src="<?php echo
htmlspecialchars($user['image_path']); ?>" alt="Profile
Image" class="img-fluid" width="200">
<?php endif; ?>
</div>
</div> <!-- Back to Users list button --> <a
href="index.php" class="btn btn-primary mt-4">Back to
Users List</a> </div> <!-- Bootstrap JS
and dependencies --> <script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script
src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.bundle.min.js"></script> </body> </html> |
edit_user.php
<?php // Include database
connection require
'db_connection.php'; // Check if the user ID is passed in the URL if (isset($_GET['id']))
{ $user_id
= $_GET['id']; // Fetch user data from the database $sql =
"SELECT users.id, users.name, users.email, users.dob, users.gender,
users.skills,
users.image_path, courses.id AS course_id,
semesters.id AS semester_id,
sections.id AS section_id,
courses.name AS course_name,
semesters.name AS semester_name,
sections.name AS section_name
FROM users
JOIN courses ON users.course_id = courses.id
JOIN semesters ON users.semester_id = semesters.id
JOIN sections ON users.section_id = sections.id
WHERE users.id = ?"; // Prepare the statement if ($stmt
= $conn->prepare($sql)) {
// Bind the user ID parameter
$stmt->bind_param('i', $user_id); // Execute the query
$stmt->execute(); // Get the result
$result = $stmt->get_result(); if ($result->num_rows > 0) {
// Fetch the user data
$user = $result->fetch_assoc();
} else {
// If no user found, redirect to index.php
header("Location: index.php");
exit();
} // Close the statement
$stmt->close(); } else {
// If there is an issue with the query, redirect to index.php
header("Location: index.php");
exit(); } } else { // If the
user ID is not set, redirect to index.php
header("Location: index.php"); exit(); } // Update the user data if the form is submitted if
($_SERVER['REQUEST_METHOD'] == 'POST') { $name =
$_POST['name']; $email =
$_POST['email']; $dob =
$_POST['dob']; $gender =
$_POST['gender']; $skills =
$_POST['skills'];
$course_id = $_POST['course'];
$semester_id = $_POST['semester'];
$section_id = $_POST['section'];
$image_path = $user['image_path']; // Handle
image upload if
(isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
$target_dir = "uploads/";
$target_file = $target_dir .
basename($_FILES["image"]["name"]);
if
(move_uploaded_file($_FILES["image"]["tmp_name"],
$target_file)) {
$image_path = $target_file;
} } // Update
the user details in the database
$update_sql = "UPDATE users
SET name = ?, email = ?, dob
= ?, gender = ?, skills = ?, course_id = ?, semester_id = ?, section_id = ?,
image_path = ?
WHERE id = ?"; if ($stmt
= $conn->prepare($update_sql)) {
// Bind parameters
$stmt->bind_param('sssssssssi', $name, $email, $dob, $gender,
$skills, $course_id, $semester_id, $section_id, $image_path, $user_id);
// Execute the update query
if ($stmt->execute()) {
// If successful, redirect to the index page
header("Location: index.php");
exit();
} else {
$error = "Error updating the record. Please try
again.";
}
// Close the statement
$stmt->close(); } } // Fetch all courses,
semesters, and sections for the select options $courses =
$conn->query("SELECT id, name FROM courses"); $semesters =
$conn->query("SELECT id, name FROM semesters"); $sections =
$conn->query("SELECT id, name FROM sections"); // Close the database
connection $conn->close(); ?> <!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> <link
href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/css/bootstrap.min.css"
rel="stylesheet"> </head> <body> <div
class="container mt-4">
<h2>Edit User</h2> <!--
Display error message if any --> <?php
if (isset($error)): ?>
<div class="alert alert-danger"><?php echo $error;
?></div> <?php
endif; ?> <!--
User Edit Form --> <form
action="edit_user.php?id=<?php echo $user['id']; ?>"
method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name"
id="name" class="form-control" value="<?php echo
htmlspecialchars($user['name']); ?>" required>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email"
id="email" class="form-control" value="<?php echo
htmlspecialchars($user['email']); ?>" required>
</div>
<div class="form-group">
<label for="dob">Date of
Birth</label>
<input type="date" name="dob"
id="dob" class="form-control" value="<?php echo
htmlspecialchars($user['dob']); ?>" required>
</div>
<div class="form-group">
<label>Gender</label><br>
<label><input type="radio"
name="gender" value="Male" <?php echo $user['gender']
== 'Male' ? 'checked' : ''; ?>> Male</label>
<label><input type="radio"
name="gender" value="Female" <?php echo
$user['gender'] == 'Female' ? 'checked' : ''; ?>> Female</label>
</div>
<div class="form-group">
<label for="skills">Skills</label>
<textarea name="skills"
id="skills" class="form-control"
rows="3"><?php echo htmlspecialchars($user['skills']);
?></textarea>
</div>
<div class="form-group">
<label for="course">Course</label>
<select name="course" id="course"
class="form-control" required>
<?php while ($course =
$courses->fetch_assoc()): ?>
<option
value="<?php echo $course['id']; ?>" <?php echo
$course['id'] == $user['course_id'] ? 'selected' : ''; ?>>
<?php echo
$course['name']; ?>
</option>
<?php endwhile; ?>
</select>
</div>
<div class="form-group">
<label
for="semester">Semester</label>
<select name="semester"
id="semester" class="form-control" required>
<?php while ($semester =
$semesters->fetch_assoc()): ?>
<option
value="<?php echo $semester['id']; ?>" <?php echo
$semester['id'] == $user['semester_id'] ? 'selected' : ''; ?>>
<?php echo
$semester['name']; ?>
</option>
<?php endwhile; ?>
</select>
</div>
<div class="form-group">
<label
for="section">Section</label>
<select name="section"
id="section" class="form-control" required>
<?php while ($section =
$sections->fetch_assoc()): ?>
<option
value="<?php echo $section['id']; ?>" <?php echo
$section['id'] == $user['section_id'] ? 'selected' : ''; ?>>
<?php echo
$section['name']; ?>
</option>
<?php endwhile; ?>
</select>
</div>
<div class="form-group">
<label for="image">Profile
Image</label>
<input type="file" name="image"
id="image" class="form-control">
<?php if (!empty($user['image_path'])): ?>
<img src="<?php echo
htmlspecialchars($user['image_path']); ?>" alt="Profile
Image" class="img-fluid" width="150">
<?php endif; ?>
</div>
<button type="submit" class="btn
btn-success">Update User</button>
<a href="index.php" class="btn
btn-secondary">Cancel</a>
</form> </div> <!-- Bootstrap JS
and dependencies --> <script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script
src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.bundle.min.js"></script> </body> </html> |
delete_user.php
<?php // Include database
connection require 'db_connection.php'; // Check if the user ID
is passed in the URL if (isset($_GET['id']))
{ $user_id = $_GET['id']; //
Prepare the delete query to remove the user from the database $sql = "DELETE FROM users WHERE id = ?"; //
Prepare the statement if ($stmt
= $conn->prepare($sql)) {
// Bind the user ID parameter $stmt->bind_param('i', $user_id);
// Execute the delete query
if ($stmt->execute()) {
// Redirect to the index page after successful deletion
header("Location: index.php");
exit();
} else {
// If there is an error, display an error message
echo "Error: Could not delete user."; }
// Close the statement
$stmt->close(); } else {
// If there is an issue with the query
echo "Error: Could not prepare the delete query."; } } else { // If the
user ID is not set, redirect to the index page
header("Location: index.php"); exit(); } // Close the database
connection $conn->close(); ?> |