Hostel Entry System: Simple CRUD Project For DBMS Using PHP + MySQL

Link Copied To Clipboard !

dbms-crud-using-php-mysql CS Subjects

Hostel Entry System is a very simple CRUD project built in order to understand common database operations using PHP + MySQL. It contains basic Session operation for login and other purposes. Let’s first understand what we are building before actually jumping into the code part.

What is Hostel Entry System ?

Hostel Entry System is a simple administrative system which is used to make new student entry for newer students who are admitted to hostel . It is a simple learning project so we will not be adding complex features. The basic workflow is:

  1. The admin logs into the system.
  2. The admin can view all students.
  3. The admin can make a new entry.
  4. The admin can edit existing entry.
  5. The admin can delete entry.
  6. The admin logs out after performing required operation.

Lets make Hostel Entry System

Without spending further time, lets get into the developing part. First, create a project and name it whatever you like. I am going to name it dbms-crud-project . Lets divide the development into following components.

  1. Database Setup
  2. Login
  3. Dashboard
  4. New Entry
  5. Edit
  6. Delete
  7. Logout

The Database Setup

Go to the project directory dbms-crud-project and make a folder called config . Make a file called db.php in which we will be writing our database configuration and connection program.

Put the following code for making connection to the database.

<?php
    $host = 'localhost';
    $user = 'user';
    $password = 'password';
    $db_name = 'dbmsproject';

    $conn = mysqli_connect($host, $user, $password, $db_name);

Replace the variable values of $host, $user, $password, $db_name according to your setup. (Note: You have to create database on your own using phpmyadmin , mysql-server or any other means.)

Now after making successful connection to database, we have to execute some sql queries for table creation. In our case, we will have three tables namely admins, address and students. We will have foreign key on students table to link student to his/her corresponding address.

Three table creation queries and their execution program are given below:

$admins_create = "CREATE TABLE IF NOT EXISTS admins (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(100) NOT NULL,
            email VARCHAR(100) NOT NULL,
            username VARCHAR(20) NOT NULL,
            password VARCHAR(256) NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )";
        $address_create = "CREATE TABLE IF NOT EXISTS address (
            id INT AUTO_INCREMENT PRIMARY KEY,
            nation VARCHAR(60) NOT NULL,
            state INT NOT NULL,
            city VARCHAR(20) NOT NULL,
            street VARCHAR(255) NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )";
        $students_create = "CREATE TABLE IF NOT EXISTS students (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(100) NOT NULL,
            email VARCHAR(100) NOT NULL,
            phone VARCHAR(20) NOT NULL,
            roll_no VARCHAR(100) NOT NULL,
            address_id INT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY(address_id) REFERENCES address(id) ON DELETE CASCADE
        )";
        if(!mysqli_query($conn, $admins_create)){
            $error =  "Error creating table: " . mysqli_error($conn);
        }
        if (!mysqli_query($conn, $address_create)) {
            $error = "Error creating admins table !";
        }
        if (!mysqli_query($conn, $students_create)) {
            $error = "Error creating admins table !";
        }

Now, we need a super user already present in our database to perform required operations. For that, we will create a admin super user using following query.

//for initial super user
         $hashed_password = password_hash('password', PASSWORD_DEFAULT);
         $insert_super_user = "INSERT INTO admins(name,email,username,password) VALUES('Admin User','admin@admin.com','admin', '$hashed_password');";
         if(!mysqli_query($conn, $insert_super_user)){
             $error = mysqli_error($conn);
         }

Remember that you have to comment this part after making first database connection otherwise it will create new admin user whenever you include your config/db.php .

Now the full db.php file looks like this.

<?php
    $host = 'localhost';
    $user = 'subash';
    $password = 'password';
    $db_name = 'dbmsproject';

    $conn = mysqli_connect($host, $user, $password, $db_name);
    
    if(!$conn){
        $error = 'Could Not Connect To Database: '. mysqli_connect_error();
    }else{
        $admins_create = "CREATE TABLE IF NOT EXISTS admins (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(100) NOT NULL,
            email VARCHAR(100) NOT NULL,
            username VARCHAR(20) NOT NULL,
            password VARCHAR(256) NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )";
        $address_create = "CREATE TABLE IF NOT EXISTS address (
            id INT AUTO_INCREMENT PRIMARY KEY,
            nation VARCHAR(60) NOT NULL,
            state INT NOT NULL,
            city VARCHAR(20) NOT NULL,
            street VARCHAR(255) NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )";
        $students_create = "CREATE TABLE IF NOT EXISTS students (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(100) NOT NULL,
            email VARCHAR(100) NOT NULL,
            phone VARCHAR(20) NOT NULL,
            roll_no VARCHAR(100) NOT NULL,
            address_id INT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY(address_id) REFERENCES address(id) ON DELETE CASCADE
        )";
        if(!mysqli_query($conn, $admins_create)){
            $error =  "Error creating table: " . mysqli_error($conn);
        }
        if (!mysqli_query($conn, $address_create)) {
            $error = "Error creating admins table !";
        }
        if (!mysqli_query($conn, $students_create)) {
            $error = "Error creating admins table !";
        }

        //for initial super user
        // $hashed_password = password_hash('password', PASSWORD_DEFAULT);
        // $insert_super_user = "INSERT INTO admins(name,email,username,password) VALUES('Admin User','admin@admin.com','admin', '$hashed_password');";
        // if(!mysqli_query($conn, $insert_super_user)){
        //     $error = mysqli_error($conn);
        // }
    }
?>

The Login Using Session

We will use simple session login for this project for simplicity. Of course you can use cookie and other if you want but let’s use session for now.

Create a file login.php in your project directory and paste the following code.

<?php
session_start();
if (isset($_SESSION['status']) && isset($_SESSION['username']) && isset($_SESSION['token'])) {
    header('Location: ./index.php');
    exit;
} else {
    if (isset($_POST['login']) && isset($_POST['username']) && isset($_POST['password'])) {
        include('functions.php');
        include('config/db.php');

        $username = validate($_POST['username']);
        $password = validate($_POST['password']);
        $query = "SELECT * FROM admins WHERE username LIKE '" . $username . "';";
        $result = mysqli_query($conn, $query);
        if (mysqli_num_rows($result) > 0) {
            while ($row = mysqli_fetch_assoc($result)) {
                if(password_verify($password, $row['password'])){
                    mysqli_close($conn);
                    //login successful
                    $_SESSION['status'] = 'logged in';
                    $_SESSION['username'] = $row['username'];
                    $_SESSION['token'] = rand(1000, 99999999999999); //just random token
                    header('Location: ./index.php');
                }
            }
        } else {
            $error = "Invalid Credentials !";
        }
    }
}

include('header.php'); ?>

<div class="container mt-5">
    <div class="row">
        <div class="col-4 mx-auto bg-light p-5">
            <p>Please Login To Continue !</p>
            <?php if (isset($error) && !empty($error)) : ?>
                <div class="error bg-danger">
                    <?=$error; ?>
                    <?php unset($error); ?>
                </div>
            <?php endif; ?>
            <hr />
            <form class="content-justify-center" method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
                <div class="mb-3">
                    <label for="username" class="form-label">Username</label>
                    <input type="text" class="form-control" name="username" required autocomplete="off">
                </div>
                <div class="mb-3">
                    <label for="password" class="form-label">Password</label>
                    <input type="password" class="form-control" name="password" required autocomplete="off">
                </div>
                <input type="submit" class="btn btn-primary" name="login" value="Login">
            </form>
        </div>
    </div>
</div>

<?php
include('footer.php');

?>

Here, we have included two files header.php and footer.php. header.php contains the header information of project and stylesheets, footer.php contains footer part and scripts included. So, create these file and put given following codes.

header.php

<?php session_start(); ?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
    <link href="assets/css/style.css" rel="stylesheet">
    <title>Hostel Entry System</title>
</head>

<body>
    <?php
    if (isset($_SESSION['status']) && isset($_SESSION['username']) && isset($_SESSION['token'])) : ?>
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <div class="container">
                <a class="navbar-brand" href="#"></a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                        <li class="nav-item">
                            <a class="nav-link" aria-current="page" href="./index.php">Home</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" aria-current="page" href="./new.php">New Entry</a>
                        </li>
                        <form class="d-flex">
                            <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search" id="search">
                        </form>
                    </ul>
                    <ul class="navbar-nav ml-auto">
                        <li class="nav-item">
                            <form class="d-flex" action="logout.php" method="POST">
                                <input type="hidden" value="<?= $_SESSION['token']; ?>" name="token" />
                                <input class="btn btn-outline-success text-white" type="submit" name="logout" value="Logout" />
                            </form>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
    <?php endif; ?>

footer.php

<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
<script src="assets/js/main.js"></script>
</body>

</html>

Also, it uses basic validate($str) function to validate the request data. Create a file functions.php and paste the following code.

<?php
    function validate($str){
        $str = trim($str);
        $str = stripslashes($str);
        $str = htmlspecialchars($str);
        return $str;
    }
?>

The Dashboard Using Session

The dashboard is index.php file in our case. So create one. The dashboard will be shown only if the admin is logged in. Meaning that, if someone is already logged in, the dashboard will be shown otherwise the user will be redirected to login.php . This applies for other files edit.php, delete.php as well.

In dashboard, we will give the option to create new entry, logout and view existing students. The admin should be able to perform edit and delete operation on each student displayed. Using simplest bootstrap layout, the dashboard page looks like this:

<?php
session_start();
if (!isset($_SESSION['status']) || !isset($_SESSION['username']) || !isset($_SESSION['token'])) {
    header('Location: ./login.php');
    exit;
}
include('header.php');
include('config/db.php');

$query = "SELECT S.*, A.nation, A.city, A.state, A.street FROM students as S INNER JOIN address as A ON S.address_id = A.id ORDER BY S.id DESC;";
$result = mysqli_query($conn, $query);
$students = array();
while ($arr = mysqli_fetch_assoc($result)) {
    $students[] = $arr;
}
mysqli_close($conn);
?>

<div class="container mt-4">

    <table class="table table-striped table-hover">
        <thead>
            <tr>
                <th scope="col">Name</th>
                <th scope="col">Roll No.</th>
                <th scope="col">Phone</th>
                <th scope="col">Email</th>
                <th scope="col">Action</th>
            </tr>
        </thead>
        <tbody id="search-container">
            <?php
            foreach ($students as $student) { ?>
                <tr class="search-item">
                    <td>
                        <p><?= $student['name']; ?></p>
                    </td>
                    <td>
                        <p><?= $student['roll_no']; ?></p>
                    </td>
                    <td>
                        <p><?= $student['email']; ?></p>
                    </td>
                    <td>
                        <p><?= $student['phone']; ?></p>
                    </td>
                    <td>
                        <button type="button" class="btn btn-info" data-bs-toggle="modal" data-bs-target="#view<?= $student['id'] ?>">
                            View
                        </button>
                        <div class="modal fade" id="view<?= $student['id'] ?>" tabindex="-1" aria-labelledby="viewmodal" aria-hidden="true">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="viewmodal"><?= $student['name'] ?></h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                    </div>
                                    <div class="modal-body">
                                        <ul class="list-group list-group-flush">
                                            <li class="list-group-item">Name: <?= $student['name'] ?></li>
                                            <li class="list-group-item">Roll No: <?= $student['roll_no'] ?></li>
                                            <li class="list-group-item">Phone: <?= $student['phone'] ?></li>
                                            <li class="list-group-item">Email: <?= $student['email'] ?></li>
                                            <li class="list-group-item">Address: <?= $student['street'] . ', ' . $student['city'] . ', State-' . $student['state'] . ', ' . $student['nation'] ?></li>
                                        </ul>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <a href="edit.php?id=<?= $student['id'] ?>" class="btn btn-primary">Edit</a>

                        <button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#delete<?= $student['id'] ?>">
                            Delete
                        </button>
                        <div class="modal fade" id="delete<?= $student['id'] ?>" tabindex="-1" aria-labelledby="deletemodal" aria-hidden="true">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="deletemodal">Are you sure ?</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                    </div>
                                    <div class="modal-body">
                                        Once confirmed, it can not be undone.
                                        <form class="d-none" id="delete-form-<?= $student['id'] ?>" action="delete.php" method="POST">
                                            <input type="hidden" value="<?= $student['id'] ?>" name="id" />
                                            <input type="hidden" value="<?= $student['address_id'] ?>" name="address_id" />
                                            <input type="hidden" value="<?= $_SESSION['token'] ?>" name="delete" />
                                        </form>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-danger" onclick="(function(){
                                            document.getElementById('delete-form-<?= $student['id'] ?>').submit();
                                        })(); return false;">
                                            Confirm
                                        </button>
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                    </div>
                                </div>
                            </div>
                        </div>

                    </td>
                </tr>
            <?php
            }
            ?>
        </tbody>
    </table>



</div>

<?php
include('footer.php');
?>

Put this code in index.php rather than dashboard.php.

Students New Entry

Upon submitting the entry form, we have to first insert address detail on address table, get the last id of that row, and insert student detail along with address_id into students table. This is because we are storing address data and student data on separate table and we have to be able to link them together using foreign key.

Create a file called new.php and paste the following code.

<?php
session_start();
if (!isset($_SESSION['status']) && !isset($_SESSION['username']) && !isset($_SESSION['token'])) {
    header('Location: ./login.php');
    exit;
} else {
    if (
        isset($_POST['new_entry']) && isset($_POST['name']) && isset($_POST['roll']) &&
        isset($_POST['email']) && isset($_POST['phone']) && isset($_POST['nation']) &&
        isset($_POST['state']) && isset($_POST['city']) && isset($_POST['street'])
    ) {

        include('functions.php');
        $name = validate($_POST['name']);
        $roll = validate($_POST['roll']);
        $email = validate($_POST['email']);
        $phone = validate($_POST['phone']);
        $nation = validate($_POST['nation']);
        $state = validate($_POST['state']);
        $city = validate($_POST['city']);
        $street = validate($_POST['street']);

        if (
            $name != null && $email != null && $phone != null && $nation != null &&
            $state != null && $city != null && $street != null
        ) {
            include('config/db.php');
            $query = "INSERT INTO address(nation,state,city,street) VALUES('$nation', '$state', '$city', '$street');";
            if (mysqli_query($conn, $query)) {
                $last_id = mysqli_insert_id($conn);
                $query = "INSERT INTO students(name,roll_no, email,phone,address_id) 
                            VALUES('$name', '$roll', '$email','$phone','$last_id');";
                if (mysqli_query($conn, $query)) {
                    $success = "New Entry Successful !";
                }else{
                    $error = "Oops! Something went wrong.";
                }
            } else {
                $error =
                    "Oops! Something went wrong.";
            }
            mysqli_close($conn);
        } else {
            $error = "Error: Some Values Are Empty !";
        }
    }
    include('header.php'); ?>
    <div class="container mt-5">
        <div class="row">
            <div class="col-6 mx-auto bg-light p-5">
                <p>New Entry Form</p>
                <?php if (isset($error) && !empty($error)) : ?>
                    <div class="error bg-danger">
                        <?= $error; ?>
                        <?php unset($error); ?>
                    </div>
                <?php endif; ?>
                <?php if (isset($success) && !empty($success)) : ?>
                    <div class="success bg-success">
                        <?= $success; ?>
                        <?php unset($success); ?>
                    </div>
                <?php endif; ?>
                <hr />
                <form class="content-justify-center" method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
                    <div class="mb-3">
                        <div class="row col-md-12">
                            <div class="col-md-6">
                                <input type="text" class="form-control" name="name" required autocomplete="off" placeholder="Full Name">
                            </div>
                            <div class="col-md-6">
                                <input type="text" class="form-control" name="roll" required autocomplete="off" placeholder="Roll Number">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="row col-md-12">
                            <div class="col-md-12">
                                <input type="email" class="form-control" name="email" required autocomplete="off" placeholder="Email Address">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="row col-md-12">
                            <div class="col-md-6">
                                <input type="text" class="form-control" name="phone" required autocomplete="off" placeholder="Phone">
                            </div>
                            <div class="col-md-6">
                                <input type="text" class="form-control" value="Nepal" name="nation" required autocomplete="off" placeholder="Nation">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="row col-md-12">
                            <div class="col-md-6">
                                <input type="number" class="form-control" name="state" required autocomplete="off" placeholder="State" min="1" max="7">
                            </div>
                            <div class="col-md-6">
                                <input type="text" class="form-control" name="city" required autocomplete="off" placeholder="City">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="row col-md-12">
                            <div class="col-md-12">
                                <input type="text" class="form-control" name="street" required autocomplete="off" placeholder="Street Address">
                            </div>
                        </div>
                    </div>
                    <input type="submit" class="btn btn-primary" name="new_entry" value="Submit">
                </form>
            </div>
        </div>

    </div>
<?php include('footer.php');
}
?>

Update Student Entry

The update process is similar except that we will execute update query instead of insert query. When the user clicks on edit button of student row on dashboard page, the page will be routed to edit.php along with the id of student. The edit form will be displayed along with existing information and upon the form submit, the update procedure will be performed. The user will be rerouted to index.php after the update process is completed.

Create a file edit.php and paste the following:

<?php
session_start();
if (!isset($_SESSION['status']) && !isset($_SESSION['username']) && !isset($_SESSION['token'])) {
    header('Location: ./login.php');
    exit;
} else {
    include('config/db.php');
    
    if (
        isset($_POST['update']) && isset($_POST['name']) && isset($_POST['roll']) &&
        isset($_POST['email']) && isset($_POST['phone']) && isset($_POST['nation']) &&
        isset($_POST['state']) && isset($_POST['city']) && isset($_POST['street'])
    ) {

        include('functions.php');
        $name = validate($_POST['name']);
        $roll = validate($_POST['roll']);
        $email = validate($_POST['email']);
        $phone = validate($_POST['phone']);
        $nation = validate($_POST['nation']);
        $state = validate($_POST['state']);
        $city = validate($_POST['city']);
        $street = validate($_POST['street']);

        $id = validate($_POST['id']);
        $address_id = validate($_POST['address_id']);

        if (
            $name != null && $email != null && $phone != null && $nation != null &&
            $state != null && $city != null && $street != null
        ) {
            $query = "UPDATE address SET nation='$nation', city='$city', state='$state', street='$street' WHERE id='$address_id';";
            if (mysqli_query($conn, $query)) {
                $last_id = mysqli_insert_id($conn);
                $query = "UPDATE students SET name='$name', roll_no='$roll', email='$email', phone='$phone' WHERE id='$id';";
                if (mysqli_query($conn, $query)) {
                    $success = "Update Successful !";
                } else {
                    $error = "Oops! Something went wrong.";
                }
            } else {
                $error =
                    "Oops! Something went wrong.";
            }
            mysqli_close($conn);
        } else {
            $error = "Error: Some Values Are Empty !";
        }
    }
    $query = "SELECT S.*, A.nation, A.city, A.state, A.street
     FROM students as S INNER JOIN address as A 
     ON S.address_id = A.id WHERE S.id = " . $_GET['id'] . ";";
    $result = mysqli_query($conn, $query);
    $student = array();
    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            $student = $row;
        }
    } else {
        header('Location: ./index.php');
        exit;
    }
    include('header.php'); ?>
    <div class="container mt-5">
        <div class="row">
            <div class="col-6 mx-auto bg-light p-5">
                <p>New Entry Form</p>
                <?php if (isset($error) && !empty($error)) : ?>
                    <div class="error bg-danger">
                        <?= $error; ?>
                        <?php unset($error); ?>
                    </div>
                <?php endif; ?>
                <?php if (isset($success) && !empty($success)) : ?>
                    <div class="success bg-success">
                        <?= $success; ?>
                        <?php unset($success); ?>
                    </div>
                <?php endif; ?>
                <hr />
                <form class="content-justify-center" method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
                    <input type="hidden" name="id" value="<?= $student['id'] ?>">
                    <input type="hidden" name="address_id" value="<?= $student['address_id'] ?>">
                    <div class="mb-3">
                        <div class="row col-md-12">
                            <div class="col-md-6">
                                <input type="text" class="form-control" name="name" required autocomplete="off" placeholder="Full Name" value="<?= $student['name'] ?>">
                            </div>
                            <div class="col-md-6">
                                <input type="text" class="form-control" name="roll" required autocomplete="off" placeholder="Roll Number" value="<?= $student['roll_no'] ?>">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="row col-md-12">
                            <div class="col-md-12">
                                <input type="email" class="form-control" name="email" required autocomplete="off" placeholder="Email Address" value="<?= $student['email'] ?>">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="row col-md-12">
                            <div class="col-md-6">
                                <input type="text" class="form-control" name="phone" required autocomplete="off" placeholder="Phone" value="<?= $student['phone'] ?>">
                            </div>
                            <div class=" col-md-6">
                                <input type="text" class="form-control" value="Nepal" name="nation" required autocomplete="off" placeholder="Nation" value="<?= $student['nation'] ?>">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="row col-md-12">
                            <div class="col-md-6">
                                <input type="number" class="form-control" name="state" required autocomplete="off" placeholder="State" min="1" max="7" value="<?= $student['state'] ?>">
                            </div>
                            <div class="col-md-6">
                                <input type="text" class="form-control" name="city" required autocomplete="off" placeholder="City" value="<?= $student['city'] ?>">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="row col-md-12">
                            <div class="col-md-12">
                                <input type="text" class="form-control" name="street" required autocomplete="off" placeholder="Street Address" value="<?= $student['street'] ?>">
                            </div>
                        </div>
                    </div>
                    <input type="submit" class="btn btn-primary" name="update" value="Update">
                </form>
            </div>
        </div>

    </div>
<?php include('footer.php');
}
?>

Delete User Entry

Deletion will be performed on delete.php page. When user clicks on delete page, a dialog will be displayed for the conformation. If confirmed, a hidden form with student_id and corresponding address_id will be send via post form along with Session token for simple data security purpose.

If, verified, the delete operation will be performed and redirected to index.php. Create a file delete.php and paste the following:

<?php
session_start();
if (!isset($_SESSION['status']) && !isset($_SESSION['username']) && !isset($_SESSION['token'])) {
    header('Location: ./login.php');
    exit;
} else {
    if (isset($_POST['delete']) && isset($_POST['id'])
            && isset($_POST['address_id']) 
            && $_POST['delete'] == $_SESSION['token']) {
        include('functions.php');
        include('config/db.php');

        $id = validate($_POST['id']);
        $address_id = validate($_POST['address_id']);
        $query = "DELETE FROM address WHERE id='$address_id';";

        if(mysqli_query($conn, $query)){
            //deleted
            header('Location: ./index.php');
            exit;
        }else{
            echo mysqli_error($conn);
        }
    }
}
?>

Logout Using Session

Since we are using session for login, the user will be automatically logged out after the session close. But we may also want to log user out even without having to close the whole session. For that, we will just unset the Session variables making it look like it has never been set, which will mean that user is not logged in, which is what user has to feel after clicking log out button.

After performing logout operation, we will redirect user to index.php which will successively redirect user to login.php because user is not logged in. We could just redirect user to login.php but we also wanna make sure it works perfectly in index.php file as well.

Create a file logout.php and paste the following:

<?php
session_start();
if (isset($_SESSION['status']) && isset($_SESSION['username']) && isset($_SESSION['token'])) {
   if(isset($_POST['logout']) && isset($_POST['token']) && $_POST['token'] == $_SESSION['token']){
       //process logout: clear session
        unset($_SESSION['status']);
        unset($_SESSION['username']);
        unset($_SESSION['token']);
   }
}
header('Location: ./index.php');
exit;
?>

Summary

We successfully implemented the CRUD operation using PHP and MySQL on our project. The Hostel Entry System can be improved and made a production level system but we will have to make some changes and add more features as well. This project is meant to demonstrate the simple CRUD operation and nothing more. So, feel free to add more features if you want.

Download

The full project is available for free on GitHub. Feel free to check it out. May be give a star if you like 🙂

GitHub Link


You May Also Like