Creating Multi User Role Based Admin Using PHP Mysql and Bootstrap
Creating Multi User Role Based Admin Using PHP Mysql and Bootstrap
Creating Multi User Role Based Admin Using PHP Mysql and Bootstrap
bootstrap
144
BY SHAHRUKH KHAN ON NOVEMBER 20, 2014PHP
Last two weeks I was quite busy with projects and hardly had any spare time left for writing blogs. I
had a huge backlog of mails requesting for tutorials. One thing I found common among them was
creating a multi user role based admin feature. I googled for the article so I can give them links but I
was not able to find useful tutorial. So i decided to make it myself for my readers. In this tutorial I will
be Creating multi user role based admin using php mysql and bootstrap library.
View Demo
In this tutorial I am not going to make a full fledged admin panel. I will show the trick using mysql database and
php logic to create multi user admin. Follow the steps below.
Step 1. Create a database and add modules,system users, role and their rights.
The first step is to create a database. I have created a database named multi-admin. Create some modules that
you will be using in your application. Check the sample sql below.
2
3 CREATE DATABASE `multi-admin`;
4 USE `multi-admin`;
5
6 CREATE TABLE IF NOT EXISTS `module` (
7 `mod_modulegroupcode` varchar(25) NOT NULL,
8 `mod_modulegroupname` varchar(50) NOT NULL,
9 `mod_modulecode` varchar(25) NOT NULL,
10 `mod_modulename` varchar(50) NOT NULL,
11 `mod_modulegrouporder` int(3) NOT NULL,
12 `mod_moduleorder` int(3) NOT NULL,
13 `mod_modulepagename` varchar(255) NOT NULL,
14 PRIMARY KEY (`mod_modulegroupcode`,`mod_modulecode`),
15 UNIQUE(`mod_modulecode`)
16 ) ENGINE=INNODB DEFAULT CHARSET=utf8;
Once you have created modules table, feed some data into it. I have used purchases, sales, stocks and Shipping,
payment and taxes. So there are 6 modules in two groups.
2
3 INSERT INTO module (mod_modulegroupcode, mod_modulegroupname, mod_modulecode, mod_modulename, mod_
4 modulegrouporder, mod_moduleorder, mod_modulepagename) VALUES
5 ("INVT","Inventory", "PURCHASES","Purchases", 2, 1,'purchases.php'),
6 ("INVT","Inventory", "STOCKS","Stocks", 2, 2,'stocks.php'),
7 ("INVT","Inventory", "SALES","Sales", 2, 3,'sales.php'),
8 ("CHECKOUT","Checkout","SHIPPING","Shipping", 3, 1,'shipping.php'),
9 ("CHECKOUT","Checkout","PAYMENT","Payment", 3, 2,'payment.php'),
("CHECKOUT","Checkout","TAX","Tax", 3, 3,'tax.php');
Create roles that will be assigned to the admins.
2
3 CREATE TABLE IF NOT EXISTS `role` (
4 `role_rolecode` varchar(50) NOT NULL,
5 `role_rolename` varchar(50) NOT NULL,
6 PRIMARY KEY (`role_rolecode`)
7 ) ENGINE=INNODB DEFAULT CHARSET=utf8;
8
9 INSERT INTO `role` (`role_rolecode`, `role_rolename`) VALUES
10 ('SUPERADMIN', 'Super Admin'),
11 ('ADMIN', 'Administrator');
Add system user/admin who will manage the application. Assign each admin with a role.
2
CREATE TABLE IF NOT EXISTS `system_users` (
3
`u_userid` int(11) AUTO_INCREMENT NOT NULL,
4
`u_username` varchar(100) NOT NULL,
5
`u_password` varchar(255) NOT NULL,
6
`u_rolecode` varchar(50) NOT NULL,
7
PRIMARY KEY (`u_userid`),
8
FOREIGN KEY (`u_rolecode`) REFERENCES `role` (`role_rolecode`) ON UPDATE CASCADE ON DELETE RES
9
TRICT
10
) ENGINE=INNODB DEFAULT CHARSET=utf8;
11
12
INSERT INTO `system_users` (`u_username`, `u_password`, `u_rolecode`) VALUES
13
('shahrukh', '123456', 'SUPERADMIN'),
14
('ronaldo', 'ronaldo', 'ADMIN');
The final step is to give each role the privilege to access modules. I have used 4 options i.e create, edit, view
and delete.
2
3 INSERT INTO `role_rights` (`rr_rolecode`, `rr_modulecode`, `rr_create`, `rr_edit`, `rr_delete`, `rr_view`) VALUES
4 ('SUPERADMIN', 'PURCHASES', 'yes', 'yes', 'yes', 'yes'),
5 ('SUPERADMIN', 'STOCKS', 'yes', 'yes', 'yes', 'yes'),
6 ('SUPERADMIN', 'SALES', 'yes', 'yes', 'yes', 'yes'),
7 ('SUPERADMIN', 'SHIPPING', 'yes', 'yes', 'yes', 'yes'),
8 ('SUPERADMIN', 'PAYMENT', 'yes', 'yes', 'yes', 'yes'),
9 ('SUPERADMIN', 'TAX', 'yes', 'yes', 'yes', 'yes'),
10
11 ('ADMIN', 'PURCHASES', 'yes', 'yes', 'yes', 'yes'),
12 ('ADMIN', 'STOCKS', 'no', 'no', 'no', 'yes'),
13 ('ADMIN', 'SALES', 'no', 'no', 'no', 'no'),
14 ('ADMIN', 'SHIPPING', 'yes', 'yes', 'yes', 'yes'),
15 ('ADMIN', 'PAYMENT', 'no', 'no', 'no', 'yes'),
16 ('ADMIN', 'TAX', 'no', 'no', 'no', 'no');
2
3 $mode = $_REQUEST["mode"];
4 if ($mode == "login") {
5 $username = trim($_POST['username']);
6 $pass = trim($_POST['user_password']);
7
8 if ($username == "" || $pass == "") {
9
10 $_SESSION["errorType"] = "danger";
11 $_SESSION["errorMsg"] = "Enter manadatory fields";
12 } else {
13 $sql = "SELECT * FROM system_users WHERE u_username = :uname AND u_password = :upass ";
14
15 try {
16 $stmt = $DB->prepare($sql);
17
18 // bind the values
19 $stmt->bindValue(":uname", $username);
20 $stmt->bindValue(":upass", $pass);
21
22 // execute Query
23 $stmt->execute();
24 $results = $stmt->fetchAll();
25
26 if (count($results) > 0) {
27 $_SESSION["errorType"] = "success";
28 $_SESSION["errorMsg"] = "You have successfully logged in.";
29
30 $_SESSION["user_id"] = $results[0]["u_userid"];
31 $_SESSION["rolecode"] = $results[0]["u_rolecode"];
32 $_SESSION["username"] = $results[0]["u_username"];
33
34 redirect("dashboard.php");
35 exit;
36 } else {
37 $_SESSION["errorType"] = "info";
38 $_SESSION["errorMsg"] = "username or password does not exist.";
39 }
40 } catch (Exception $ex) {
41
42 $_SESSION["errorType"] = "danger";
43 $_SESSION["errorMsg"] = $ex->getMessage();
44 }
45 }
46 // redirect function is found in functions.php page
47 redirect("index.php");
48 }
Once you are logged in you are redirected to dashboard.php where you will see the menu/modules that are
assigned as per your role. Your role is saved in session when you are logged in.
2
3 // if the rights are not set then add them in the current session
4 if (!isset($_SESSION["access"])) {
5
6 try {
7
8 $sql = "SELECT mod_modulegroupcode, mod_modulegroupname FROM module "
9 . " WHERE 1 GROUP BY `mod_modulegroupcode` "
10 . " ORDER BY `mod_modulegrouporder` ASC, `mod_moduleorder` ASC ";
11
12 $stmt = $DB->prepare($sql);
13 $stmt->execute();
14 // modules group
15 $commonModules = $stmt->fetchAll();
16
17 $sql = "SELECT mod_modulegroupcode, mod_modulegroupname, mod_modulepagename, mod_modulecode, m
18 od_modulename FROM module "
19 . " WHERE 1 "
20 . " ORDER BY `mod_modulegrouporder` ASC, `mod_moduleorder` ASC ";
21
22 $stmt = $DB->prepare($sql);
23 $stmt->execute();
24 // all modules
25 $allModules = $stmt->fetchAll();
26
27 $sql = "SELECT rr_modulecode, rr_create, rr_edit, rr_delete, rr_view FROM role_rights "
28 . " WHERE rr_rolecode = :rc "
29 . " ORDER BY `rr_modulecode` ASC ";
30
31 $stmt = $DB->prepare($sql);
32 $stmt->bindValue(":rc", $_SESSION["rolecode"]);
33
34 $stmt->execute();
35 // modules based on user role
36 $userRights = $stmt->fetchAll();
37
38 $_SESSION["access"] = set_rights($allModules, $userRights, $commonModules);
39
40 } catch (Exception $ex) {
41
42 echo $ex->getMessage();
43 }
}
In the above script all the data are passed into a function named set_rights() which return an array based on user
roles.
2
function set_rights($menus, $menuRights, $topmenu) {
3
$data = array();
4
5
for ($i = 0, $c = count($menus); $i < $c; $i++) {
6
7
$row = array();
8
for ($j = 0, $c2 = count($menuRights); $j < $c2; $j++) {
9
if ($menuRights[$j]["rr_modulecode"] == $menus[$i]["mod_modulecode"]) {
10
if (authorize($menuRights[$j]["rr_create"]) || authorize($menuRights[$j]["rr_edit"]) ||
11
authorize($menuRights[$j]["rr_delete"]) || authorize($menuRights[$j]["rr_view"])
12
){
13
14
$row["menu"] = $menus[$i]["mod_modulegroupcode"];
15
$row["menu_name"] = $menus[$i]["mod_modulename"];
16
$row["page_name"] = $menus[$i]["mod_modulepagename"];
17
$row["create"] = $menuRights[$j]["rr_create"];
18
$row["edit"] = $menuRights[$j]["rr_edit"];
19
$row["delete"] = $menuRights[$j]["rr_delete"];
20
$row["view"] = $menuRights[$j]["rr_view"];
21
22
$data[$menus[$i]["mod_modulegroupcode"]][$menuRights[$j]["rr_modulecode"]] = $row;
23
$data[$menus[$i]["mod_modulegroupcode"]]["top_menu_name"] = $menus[$i]["mod_modulegroupname"
24
];
25
}
26
}
27
}
28
}
29
30
return $data;
31
}
32
33
// this function is used by set_rights() function
34
function authorize($module) {
35
return $module == "yes" ? TRUE : FALSE;
36
}
Once you have all the modules based on your role in a session variable. Display it as list menu.
2
3 <ul>
4 <?php foreach ($_SESSION["access"] as $key => $access) { ?>
5 <li>
6 <?php echo $access["top_menu_name"]; ?>
7 <?php
8 echo '<ul>';
9 foreach ($access as $k => $val) {
10 if ($k != "top_menu_name") {
11 echo '<li><a href="' . ($val["page_name"]) . '">' . $val["menu_name"] . '</a></li>';
12 ?>
13 <?php
14 }
15 }
16 echo '</ul>';
17 ?>
18 </li>
19 <?php
20 }
21 ?>
22 </ul>
2
3 <!-- for creating purchase function -->
4 <?php if (authorize($_SESSION["access"]["INVT"]["PURCHASES"]["create"])) { ?>
5 <button class="btn btn-sm btn-primary" type="button"><i class="fa fa-plus"></i> ADD PURCHASE</button>
6 <?php } ?>
7
8 <!-- for updating purchase function -->
9 <?php if (authorize($_SESSION["access"]["INVT"]["PURCHASES"]["edit"])) { ?>
10 <button class="btn btn-sm btn-info" type="button"><i class="fa fa-edit"></i> EDIT</button>
11 <?php } ?>
12
13 <!-- for view purchase function -->
14 <?php if (authorize($_SESSION["access"]["INVT"]["PURCHASES"]["view"])) { ?>
15 <button class="btn btn-sm btn-warning" type="button"><i class="fa fa-search-plus"></i> VIEW</button>
16 <?php } ?>
17
18 <!-- for delete purchase function -->
19 <?php if (authorize($_SESSION["access"]["INVT"]["PURCHASES"]["delete"])) { ?>
20 <button class="btn btn-sm btn-danger" type="button"><i class="fa fa-trash-o"></i> DELETE</button>
21 <?php } ?>
2
3 // paste this in login page
4 if (isset($_SESSION["user_id"]) && $_SESSION["user_id"] != "") {
5 // if logged in send to dashboard page
6 redirect("dashboard.php");
7 }
8
9 // paste this in any page which require admin authorization
10 if (!isset($_SESSION["user_id"]) || $_SESSION["user_id"] == "") {
11 // not logged in send to login page
12 redirect("index.php");
13 }
You can also add another layer of security check for each modules pages if you want. In case if user is trying to
access a modules using direct page URL but is not assigned for, they must not passed this security check.
2
3 $status = FALSE;
4 if ( authorize($_SESSION["access"]["INVT"]["PURCHASES"]["create"]) ||
5 authorize($_SESSION["access"]["INVT"]["PURCHASES"]["edit"]) ||
6 authorize($_SESSION["access"]["INVT"]["PURCHASES"]["view"]) ||
7 authorize($_SESSION["access"]["INVT"]["PURCHASES"]["delete"]) ) {
8 $status = TRUE;
9 }
10
11 if ($status === FALSE) {
12 die("You dont have the permission to access this page");
13 }
2
3 session_start();
4 $_SESSION = array();
5 unset($_SESSION);
6 session_destroy();
7 header("location:index.php");
8 exit;
View Demo