how to assign multiple role to a users using php code example
Example 1: php permission system
public function hasRole($role_name) {
return isset($this->roles[$role_name]);
}
public static function insertPerm($role_id, $perm_id) {
$sql = "INSERT INTO role_perm (role_id, perm_id) VALUES (:role_id, :perm_id)";
$sth = $GLOBALS["DB"]->prepare($sql);
return $sth->execute(array(":role_id" => $role_id, ":perm_id" => $perm_id));
}
public static function deletePerms() {
$sql = "TRUNCATE role_perm";
$sth = $GLOBALS["DB"]->prepare($sql);
return $sth->execute();
}
Example 2: php permission system
object(PrivilegedUser)
["roles":"PrivilegedUser":private]=>
array(1) {
["Admin"]=>
object(Role)
["permissions":protected]=>
array(4) {
["addUser"]=>bool(true)
["editUser"]=>bool(true)
["deleteUser"]=>bool(true)
["editRoles"]=>bool(true)
}
}
}
["fields":"User":private]=>
array(4) {
["user_id"]=>string(1) "2"
["username"]=>string(7) "mpsinas"
["password"]=>bool(false)
["email_addr"]=>string(0) ""
}
}
Example 3: php permission system
<?php
class PrivilegedUser extends User
{
private $roles;
public function __construct() {
parent::__construct();
}
public static function getByUsername($username) {
$sql = "SELECT * FROM users WHERE username = :username";
$sth = $GLOBALS["DB"]->prepare($sql);
$sth->execute(array(":username" => $username));
$result = $sth->fetchAll();
if (!empty($result)) {
$privUser = new PrivilegedUser();
$privUser->user_id = $result[0]["user_id"];
$privUser->username = $username;
$privUser->password = $result[0]["password"];
$privUser->email_addr = $result[0]["email_addr"];
$privUser->initRoles();
return $privUser;
} else {
return false;
}
}
protected function initRoles() {
$this->roles = array();
$sql = "SELECT t1.role_id, t2.role_name FROM user_role as t1
JOIN roles as t2 ON t1.role_id = t2.role_id
WHERE t1.user_id = :user_id";
$sth = $GLOBALS["DB"]->prepare($sql);
$sth->execute(array(":user_id" => $this->user_id));
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$this->roles[$row["role_name"]] = Role::getRolePerms($row["role_id"]);
}
}
public function hasPrivilege($perm) {
foreach ($this->roles as $role) {
if ($role->hasPerm($perm)) {
return true;
}
}
return false;
}
}