All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Admin And User Login In PHP MySQL

Last Updated : Jul 1, 2023

Admin And User Login In PHP MySQL

In this article we will show you the solution of admin and user login in php mysql, here first we need to create login form with some input fields and database connection.

As we know valid users and admin only successfully gets login otherwise it won’t allow anyone to interact with database because it leads to unauthorized person can access database data easily.

If they are valid user or admin then it can redirect them to their home page.

Step By Step Guide On Admin And User Login In PHP MySQL :-

Here we developed login form with two input fields ‘Name, Password’ there admin have to enter login details then we can check whether user or admin is valid or not by their login details.

If they are entered valid login details then user or admin navigate to their home page otherwise we can’t move to any other page and at valid admin home page we provided all database data, admin only can view all database data from server and at valid user’s home page we provided welcome message then have logout option.

<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form action="validate.php" method="post">
<h1>Login</h1>
<input type="text" placeholder="Username" name="un" value="">
<input type="password" placeholder="Password" name="psw" value="">
<input class="button" type="submit" name="submit" value="Sign In">
</form>
</body>
</html>
conn.php
<?php
session_start();
$conn = "";
$conn = mysqli_connect("localhost","root","","dbase");
if (!$conn) {
    echo "Connection failed!";
}
?>
validate.php
<?php include('conn.php')?>
<?php
if (isset($_POST["submit"])) {
    $username = $_POST["un"];
    $password = $_POST["psw"];
    $res=mysqli_query($conn, "SELECT * FROM users where username='$username' AND password='$password'");
    $row = mysqli_fetch_assoc($res);
        if(($row['user_type'] == 'user') && ($row['username'] == $username)) {
            $_SESSION['user']=$row['username'];
                header("location: user.php");
        }
        else if(($row['user_type'] == 'admin') && ($row['username'] == $username)) {
            $_SESSION['user']=$row['username'];
                header("location: admin.php");
        }
        else if(($username == '') && ($password == '')) {
            echo "<script language='javascript'>";
            echo "alert('Invalid Inputs')";
            echo "</script>";
        }
        else {
            echo "<script language='javascript'>";
            echo "alert('WRONG INFORMATION')";
            echo "</script>";
            die();
        }
    }
?>
admin.php
<?php include('conn.php')?>
<h2>Welcome <?php echo $_SESSION['user'] ?><span style="font-size:15px"><i>(Admin)</i></span></h2>
<br>
<h3><i>Database Users All Details</i></h3>
<?php
$res=mysqli_query($conn, "SELECT * FROM users");
if(mysqli_num_rows($res) > 0)
{
  echo'<table border=1>
 <tr>
  <th>User Name</th>
        <th>User Type</th>
  <th>Email</th>
        <th>Password</th>
    </tr>';
    while($r = mysqli_fetch_array($res))
 {
    echo '<tr>
        <td>'.$r["username"].'</td>
        <td>'.$r["user_type"].'</td>
        <td>'.$r["email"].'</td>
        <td>'.$r["password"].'</td>
    </tr>';
    }
    echo '</table>
    <a href="logout.php">Logout</a>';
}
?>
user.php
<?php include('conn.php')?>
<h2>Welcome <?php echo $_SESSION['user'] ?> <span style="font-size:15px"><i>(user)</i></span></h2>
<a href="logout.php">Logout</a>
logout.php
<?php
session_start();
session_unset();
session_destroy();
header("Location: index.html");
?>
  1. A php script can be placed anywhere in the document. A php script starts with <?php and end with ?>.
  2. The default file extension for php files is “.php” and php statements end with ‘;’ semicolon.
  3. Here we developed index page with login form layout there we defined two input fields ‘Name, Password’ users or admins needs to fill their login details.
  4. In login form we need to confirm two things, at input element definition we have to define ‘name’ attributes with some values ‘un, psw’ and in form tag need to have method attribute with ‘post’ value, action attribute with ‘validate.php’ external php file which is used to redirect us to next processing page.
  5. In conn.php we executed database connection by using ‘mysqli_connect()’ method which contains database, server connection details that is referred by variable ‘$conn’ and then using if condition we checking database is exists or not.
  6. Above seen database connection file mostly useable file we added at necessary pages by using ‘include()’ method which is help us to use at any page in website some line of code repeatedly.
  7. If database exists then validate.php executing, there we using isset() method to check whether post method is set or not and then ‘name, password’ input fields collected and stored on respective variables ‘$username, $password’.
  8. Using select query with condition as user inputs same with database row data then we executing query on database which result stored on variable ‘$res’ by mysqli_query() with the help of database connection $conn. Then mysqli_fetch_assoc() used to collect table ‘users’ details which array of values stored on variable ‘$row’.
  9. Using if condition we checking whether user inputs match with database table data and that user’s user type is ‘user’ then we storing user name on session variable and redirect to user’s home page ‘user.php’ otherwise it displays error message.
  10. In user.php file we displayed user name by session with welcome message and we provided logout option when user clicks on it we redirect them to index page.
  11. Using another if condition we checking whether user inputs match with database table data and that user’s user type is ‘admin’ then we storing admin name on session variable and redirect to admin’s home page ‘admin.php’ otherwise it displays error message.
  12. In admin.php we started session and displaying admin name with welcome message then we checking whether row number count by ‘mysqli_num_rows()’ method using if condition.
  13. Within that we defined table with four coulmns ‘User Name,User Type,Email,Password’ after header column we needs to use ‘mysqli_fetch_array()’ method for access array of table ‘users’ data using while loop.
  14. Then fetching table ‘users’ data as row by row and displayed on table by specifying database values ‘$r["username"],$r["user_type"],$r["email"], $r["password"]’ between <td> table coulmns and we provided logout option which redirect us to index page.
  15. At logout.php page we destroyed session variables and session by session_unset(),session_destroy() methods then redirect to index page.
  16. Finally confirm one thing is every table tag had their closing tag otherwise we can’t get table structure.

Conclusion :-

In conclusion now we are able to know how to create admin and user login page in php.

When work with php we need to create and process php files at server location and then we need to start the server before execute the program.

When we executing this program on browser we can see login form there user or admin needs to provide their name and password then it will redirect them to their home page at we can see welcome message with their name and if admin login then it displays whole database table users details in table if they provide valid details otherwise it throws error and we can’t move to any other page.

I hope this article on admin and user login in php mysql helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Pragati

Experienced coding content writer who enjoys breaking down complex concepts in programming languages like Java, Python, C, and C++. Over three years of experience producing interesting and relevant content for a variety of entities. Committed to providing concise and easy-to-understand articles that assist readers in easily understanding technology and industry trends in the world of coding and software development.

Follow Pragati On Linkedin 🡪