php user roles permissions mysql 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
<?php
class Role
{
protected $permissions;
protected function __construct() {
$this->permissions = array();
}
public static function getRolePerms($role_id) {
$role = new Role();
$sql = "SELECT t2.perm_desc FROM role_perm as t1
JOIN permissions as t2 ON t1.perm_id = t2.perm_id
WHERE t1.role_id = :role_id";
$sth = $GLOBALS["DB"]->prepare($sql);
$sth->execute(array(":role_id" => $role_id));
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$role->permissions[$row["perm_desc"]] = true;
}
return $role;
}
public function hasPerm($permission) {
return isset($this->permissions[$permission]);
}
}