search
HomeBackend DevelopmentPHP Tutorialphp如何实现人员权限管理

php如何实现人员权限管理

Jun 06, 2016 pm 08:40 PM
phpRole Permissions

php实现人员权限管理的方法:首先做一个管理员的页面,并实现选择用户的功能;然后用jquery的函数实现选择相应用户功能;接着创建处理页面【chuli.php】;最后修改用户对应的角色并保存即可。

php如何实现人员权限管理

php如何实现人员权限管理?

php实现人员权限管理(管理员页面)

控制人员权限用的最多的应该是OA办公自动化系统和像ERP,CRM,CMS这样的管理系统,就是通过控制用户的权限来控制其拥有的角色和功能,比如管理员可以拥有所有权限和功能,前台只能拥有登记和通报信息等。

一般标准的权限管理都会有5张数据表来控制,形成一个W型的连接关系,如下

         企业微信截图_15923613041799.png

 

看看表的结构

1.用户表 2.用户角色对应表 3.角色表 4.角色功能对应表 5.功能表

 

首先我们来做一个管理员的页面,这个页面能显示所有用户,并且能看到他们对应的角色,这里我们还能修改他们的角色,先看看效果

 

 一步步来,先写出来选择用户的功能,当然,显示的用户都是从用户表里加载过来的

请选择用户:
  <select id="sel">
      <option>请选择</option>
    <?php
    require "../DataBase.class.php";
    $db=new DataBase();
    $sql="select * from users";
    $arr=$db->Query($sql);
    foreach($arr as $v){
        echo "<option value=&#39;{$v[0]}&#39;>{$v[2]}</option>";

        }
    ?>
  </select>

再把角色的复选框写出来 ,附带那个保存按钮也写出来吧

请选择角色:
    <?php
    $sql2="select * from juese";
    $arr2=$db->Query($sql2);
    foreach($arr2 as $k){
        
        echo "<input type=&#39;checkbox&#39; class=&#39;ck&#39; value=&#39;{$k[0]}&#39;>$k[1]";
        
        }
    ?>



<div><input type="button" id="save"  value="保存"/></div>

界面写完了,下面实现功能代码

功能1.选择相应用户,默认显示他对应的角色(复选框的默认选中)

用jquery的函数实现(页面开头先引入Jquery)

$("#sel").change(function (){
        var uid=$("#sel").val();       //取到下拉选择的用户
        $.ajax({                        //调用ajax
                url:"chuli.php",
                data:{uid:uid},
                type:"POST",
                dataType:"TEXT",
                success: function(data){
                        var js=data.trim().split("|");    //返回的字符串只有行,进行拆分和去空格,然后得到的是角色数组
                        var ck=$(".ck");                //获取所有复选框的值,交给了一个ck数组
                        ck.prop("checked",false);        //先清空上次选择用户时留下的复选内容
                        for(var i=0;i<ck.length;i++)    //遍历判断
                        {
                            var v=ck.eq(i).val();        //v代表的是每个复选框的值
                            if(js.indexOf(v)>=0){        //判断一下,返回的角色表中的数据是否存在,用的 indexOf方法,如果不存在则返回-1
                                ck.eq(i).prop("checked",true);  //将数据库存在的角色对应的属性设置为选中

                                }
                            }



                    }
            })

});

下面是处理页面chuli.php

<?php
$uid=$_POST["uid"];
require "../DataBase.class.php";
$db=new DataBase();
$sql="select jueseid from userinjuese where userid=&#39;{$uid}&#39;";
echo $db->StrQuery($sql);



?>

如果看不明白的话,看看这个返回字符串的类怎么写的

<?php
class DataBase
{
    public $host="localhost";
    public $uid = "root";
    public $pwd = "";
    public $dbname = "mydb";

    //成员方法
    public function Query($sql,$type=1)
    {
        $db = new MySQLi($this->host,$this->uid,$this->pwd,$this->dbname);
        $r = $db->query($sql);

        if($type==1)
        {
            return $r->fetch_all();
        }
        else
        {
            return $r;
        }
    }

    //返回字符串的方法
    public function StrQuery($sql,$type=1)
    {
        $db = new MySQLi($this->host,$this->uid,$this->pwd,$this->dbname);
        $r = $db->query($sql);

        if($type==1)
        {
            $attr = $r->fetch_all();
            $str = "";
            foreach($attr as $v)
            {
                $str .= implode("^",$v)."|";
            }

            return substr($str,0,strlen($str)-1);
           }

        else
        {
            return $r;
        }
    }

    //返回JSON
    public function jsonquery($sql,$type=1)
    {
        $db = new MySQLi($this->host,$this->uid,$this->pwd,$this->dbname);
        $r = $db->query($sql);

        if($type==1)
        {
            return json_encode($r->fetch_all(MYSQLI_ASSOC));
        }
        else
        {
            return $r;
        }
    }
}

 

功能2.修改用户对应的角色,并且保存

$("#save").click(function (){        //&#39;保存&#39;按钮的点击事件
        var uid=$("#sel").val();    //获取下拉选择的用户
        var str="";
        var ck=$(".ck");            //获取所有复选框的值,放到ck数组
        for(var i=0;i<ck.length;i++)
        {
            if(ck.eq(i).prop("checked"))   //判断,如果复选框的值为选中
            {
                str+=ck.eq(i).val()+",";  //将选中的复选框值用“,”拼接起来交给str

                }



            }
        str=str.substr(0,str.length-1);  //截取一下str,因为最后尾部会多余一个符号
        $.ajax({
            url:"save.php",
            data:{uid:uid,js:str},          //将用户和拼接好的已选择复选内容交给处理页面
            dataType:"TEXT",
            type:"POST",
            success: function(data){

                alert("保存成功")

                }





            })




    })

处理页面

<?php
$uid=$_POST["uid"];      //获取到了传递的用户
$js=$_POST["js"];        //获取到了传递过来的已选择的复选框内容
require "../DataBase.class.php";
$db=new DataBase();
$sql="delete from  userinjuese where userid=&#39;{$uid}&#39;"; //先把数据库中原来用户的角色清空,不然修改起来会麻烦
$db->Query($sql,0);
$vv=explode(",",$js);        //将复选框内容拆分,因为传来的是一个,隔开的长字符串,得到的vv是一个数组
foreach($vv as $v){         //遍历这个数组
$sql2="insert into userinjuese values(&#39;&#39;,&#39;{$uid}&#39;,&#39;{$v}&#39;)"; //依次写入数据库
    $db->Query($sql2,0);

}


?>

功能完成了。结束

更多相关技术知识,请访问PHP中文网

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment