Hi, if you want to manage different role-based users are login access to the single login form and go to your own account. This tutorial helps you to build Multi User Role Based Login in PHP with MySQL PDO. Show
The role based user login access nowadays is one of the most popular features of a modern web application. For example in a school system, you manage two roles, professor and students, you can give restricted permission to each role. Such as the role of the student, they do not only access the professor's account while changing their profile, etc. and more can be personalized to manage depending on the requirement. OK, let's continue the tutorial and we've built a multi user role based login system with restricted permission to manage different roles. Table Content1. Where Use Of Multi User Role Based Login System2. Project Structure3. Database and Table4. connection.php5. index.php [ PHP Login Form ]5.1 PHP Code For Login Form5.2 Login Codes Logic Explanation6. register.php [ PHP Registration Form ]6.1 PHP Code For Registration Form6.2 Registration Codes Logic Explanation7. admin_home.php8. employee_home.php9. user_home.php10. logout.php1. Where Use Of Multi User Role Based Login SystemFor example in a management system of the company. Three admin, user, and employee roles are accessed in a single login form. Suppose the user's role is to log in successfully and go to the user's account, seeing their attendance, work, task, etc. In the same other roles admin and employee use the same form of a login and have their account and work with their account as they need. This tutorial helps to not create a separate roles login page. Login access functionality in the single login form to easily handle different roles as well as depend on your custom requirement. 2. Project StructureSee the structure of the project directory inside C:\xampp\htdocs location below. Because I have the XAMPP server installed in C: drive. I created 7 files below for a multi user role based login system to develop completely. 1. connection.php 2. index.php 3. register.php 4. admin_home.php 5. employee_home.php 6. user_home.php 7. logout.php 3. Database and TableTo create a database and table, import and run below SQL code your PhpMyAdmin. I have already inserted admin dumping records in a table here. Because this project only uses one super admin. Note – The column in the table role field indicates the particular name of the role to be added by new users. 4. connection.phpI create a database connection in this file by the PDO extension of PHP. 5. index.php [ PHP Login Form ]I create a login form in this file with two input boxes and one select option. The input box that takes email and password, a select option that contains the role name admin, user, and employee which selects login access by specific role. PHP Login Form Visually Below This Type :5.1 PHP Code for Login FormBelow PHP login codes responsible for identifying the user's authenticated email, password, and role name according to the specific role selection and verifying in the database. if all details are present in the table then the session will start according to the specific role name selection and roles will allow access to the own dashboard. otherwise, the required message will be displayed. I know lengthy but not difficult move to logic code explanation below, you'll comprehend the full logic of the codes. 5.2 Login Codes Logic ExplanationRow no 2 – Include the configuration file of the database using the function require_once. Because we fire SQL select query for user login through $db database object. Row no 4 – Using session_start() function we start the session. Row no 6 to 17 – Three if conditions, get different roles name session keys (admin_login, employee_login, user_login). If both are found then the function header() sends the roles specific account. This is the main objective of the session as the active login of any user will not directly access the login page their account required logout.
Row no 19 – If condition, get the name attribute value login form button btn_login using the method $_REQUEST[ ] array. And the isset() function targets this attribute value by clicking the event.
Row no 21 to 23 – Using $_REQUEST [ ] variable method get all values txt_email, txt_password and txt_role by name attribute in the login form fields. Get able form fields all values store in created $email, $password & $role variables.
Row no 25 to 33 – three if and else if condition, empty() function checks that all variable value is not null.
Row no 34 – else if condition check each variable value returns true.
Row no 36 to 44 – Open the try / catch block, apply the select PDO query in the prepare() statement and select all records. bindParam() function binds the value of the variables :uemail, :upassword and :urole in query place. And, above all, the values of $email, $password, and $role variables persist. execute() function execute the query statement.
Row no 46 to 51 – PDOStatement:: fetch method returns row from the result set. PDO:: FETCH_ASSOC parameter informs PDO to return array value indexed by table column email, password and role. The $row is an array. All values are stored created new variables $dbemail, $dbpassword and $dbrole.
Row no 52 – if condition checks the variables $email, $password, and $role do not return null.
Row no 54 – if condition test results the number of rows returnable by rowCount() function is greater than zero (>0).
Row no 56 – if condition, the user typeable form field values and table values must be matched using == operator check. Note: – The == use of the operator for both operand values is equal to or not.
Row no 58 to 80 – Then the switch statement occurred, above all condition is true. And within the switch case statement, we store the values of the role name by the $dbrole variable since that variable holds the values of the role name that are already discussed above by the $row array.
case "admin": If the name of the admin role detected that case, assign the admin_login session key in $_SESSION[ ] array. Apply the admin login message and the header() function will keep this message within 3 seconds, it will be sent in the admin_home.php page created under the admin folder and break it. case "employee": If the name of the employee role was found as the case became, assign employee_login session key in $_SESSION[ ] array. Push login message for employees. The function header() keeps the message within 3 seconds, Send it to the employee_home.php page that was built in the employee folder and break it. case "user": When the user name was found as the case occurred, In $_SESSION[ ] array assign the session key name user_login. Push user login message and keep the message in 3 seconds with header() function, send it to user_home.php page that was built in the user folder and break it. default: – The case statement of the switch provides the default state case. Attach error messages like wrong email or password or role inside the default case. Note – I haven't explained else condition see any else condition detecting unique condition-based error message. And the error message is defined in the array variable $errorMsg[ ]. 6. register.php [ PHP Registration Form ]Create a registration form for new user data to be registered in the database in this file. This form contains three input boxes and one option to select. The three input box that takes username, email, password and the selection option that takes the name of the role. Following the registration form, which is responsible for adding different roles in the database by choosing a new user. PHP Registration Form Visually Below This Type :6.1 PHP Code For Registration FormBelow are PHP codes that register new user data to the database. Validation is also provided in these codes and if you have already registered username or user email, the message would indicate the email or username already exists. Extra these codes validate the right email format and the length of the password must be 6 characters. It will handle the registration process along with suitable validation. Below codes a few long but not a complicated jump to the explanation of the logic codes to easily comprehend the logic. 6.2 Registration Codes Logic ExplanationRow no 3 – Add a connection file to the database using the require_once function. Via the database file object $db, to fire PDO queries. Row no 5 – If condition, use the method $_REQUEST[ ] array to get the name attribute value registration form button btn_register. And the isset() function targets the value of this attribute by clicking on the event.
Row no 7 to 10 – Using $_REQUEST[ ] array method gets all txt_username, txt_email, txt_password, and txt_role values by name attribute in the fields of the registration form. Get form fields that store all values in created variables $username, $email, $password & $role.
Row no 12 to 29 – If and else condition verify form fields all values not null using the function empty(). As well as checking valid email address format and password length at least 6 characters must be needed. filter_var – Filter a variable with a specified filter ( according to FILTER_VALIDATE_EMAIL – The FILTER_VALIDATE_EMAIL filter validates an e-mail address ( according to php.net ). I filter $email variable value here that is taken from user input to check valid email address format. strlen() – Returns the length of the given string. ( according to php.net ). Here I check the variable value of $password that takes user inputs less than six (< 6) or not.
Row no 32 to 39 – Inside the try / catch block discussion. Apply PDO select query under the prepare() statement and a select username and email values from the table. bindParam() function bind the parameter :uname, :uemail values placed within select query. And both values consistent by $username and $email variables. The function execute() executes a PDO query statement. PDOStatement:: fetch method extracts a row from the set of results. PDO:: FETCH_ASSOC parameter tells PDO to retrieve array value indexed by username and email of the table column. The array is $row.
Row no 41 to 46 – If and if-else condition checks the new user has entered the username and the email value already exists from the table or not.
Row no 48 to 60 – else if condition, the isset() function checks that the $errorMsg variable does not return any error message, and applies the PDO insert query in prepare() statement. The function bindParam() binds the values :uname, :uemail, :upassword and :urole in the insert query. All parameter values carry variables along with $username, $email, $password, and $role. Finally, the execute() function executes the insert query statement, displays the register successfully message and the header() function keeps this message at 4 seconds and sends it to index.php page. 7. admin_home.phpRow no 8 – Verify that the admin session key admin_login has not been found then returns the header() function onto the index page. Because the admin role does not have direct access to the admin page. The session key is confirmation from the index/login form that the admin is authenticated. Row no 13 – This condition checks whether the employee's role session key employee_login is found then the header() function sends to the employee_home.php page. Because the admin page doesn't allow permissions employee role to access this page. Row no 18 – Also this condition works above, if the user's role user_login session key is found then the function header() delivers to the user_home.php page. The user role does not access the admin page because permissions were still not allowed on this page. Row no 23 to 29 – Get admin_login session key to admin role and view e-mail admin value using echo. Admin Account Visually Below This Type :8. employee_home.phpRow no 9 – Here scan the employee_login session key of the employee role that was not found then sending the header() function on the index page. Row no 14 – Here we get admin_login session key if you find sending by header function to admin_home.php page. Because the employee account has not allowed admin permissions to access this page. Row no 19 – The same here we get user_login session key of user role if we consider sending by header() function to user_home.php page. Not to access the employee account or page, either, the user role. Row no 24to 30 – Take employee_login session key of employee role and use echo to display employee email address value. Employee Account Visually Below This Type :9. user_home.phpRow no 9 – We apply admin and employee page account tactics on this page. We get user_login session key of user role, if not found then the header() function transfers immediately to the index page because any user role does not directly access the user account. Row no 14 – In this condition we obtain the admin_login session key of the admin role if it is detected then sending by header() function to the admin account. Row no 19 – Exactly here we use the same techniques of the above condition in this condition. We receive employee_login session key of employee role if find then deliver by header() function to employee account. Row no 24 to 30 – Finally, accept user_login session key of user role and use echo to display active user login email address. User Account Visually Below This Type :10. logout.phpIn this file, along with click logout hyperlink, we destroy the session from the whole role's account and send it all to the index/login page.
Congrats to completely develop multi user role based login system. How will you create a multi user form login administrator and user with php MySQL?In this case, you have to use multiple session variables like $_SESSION['email'] and $_SESSION['type']. Here, $email will be the username of particular user and $type will be the type of user like admin, branch admin, reporter, accountant etc.
How can I login as administrator in PHP?In this article, we will be using the XAMPP server.. Create Database: First, we will create a database named 'geeksforgeeks' (you can give any name to your database). ... . Create Table: Create a table named 'adminlogin' with 3 columns to store the data. ... . Create Table Structure: The table “adminlogin” contains three fields.. How do I retrieve data from the database of a particular user after logging in PHP?Retrieve or Fetch Data From Database in PHP. SELECT column_name(s) FROM table_name.. $query = mysql_query("select * from tablename", $connection);. $connection = mysql_connect("localhost", "root", "");. $db = mysql_select_db("company", $connection);. $query = mysql_query("select * from employee", $connection);. |