mysql创建库 创建用户 并授权用户可使用的库 - mysql权限管理例子
$dbname="ceshi1222_com"; $username="user222"; //创建库 $sql="CREATE DATABASE {$dbname} DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci"; if(mysqli_real_query($con,$sql)){echo "创建库成功<br>";}else{echo "创建库失败<br>";} //创建用户 $sql="CREATE USER '{$username}'@'localhost' IDENTIFIED BY '密码'"; if(mysqli_real_query($con,$sql)){echo "创建用户成功<br>";}else{echo "创建用户失败<br>";} //保险起见 可以同时创建一个127.0.0.1地址的 省的以后麻烦 $sql="CREATE USER '{$username}'@'127.0.0.1' IDENTIFIED BY '密码'"; if(mysqli_real_query($con,$sql)){echo "创建用户成功<br>";}else{echo "创建用户失败<br>";} //赋予USAGE权限 详细了解请搜索 USAGE权限 //字面意思: 授予使用权 在所有库.所有表 $sql="GRANT USAGE ON *.* TO '{$username}'@'localhost'"; if(mysqli_real_query($con,$sql)){echo "赋予USAGE权限成功<br>";}else{echo "赋予USAGE权限失败<br>";} $sql="GRANT USAGE ON *.* TO '{$username}'@'127.0.0.1'"; if(mysqli_real_query($con,$sql)){echo "赋予USAGE权限成功<br>";}else{echo "赋予USAGE权限失败<br>";} //赋予管理某个库的权限 详情可以搜索 mysql GRANT命令 //字面意思: 授予所有特权 在某库的所有表 TO 某用户 $sql="GRANT ALL PRIVILEGES ON `{$dbname}`.* TO `{$username}`@'localhost'"; if(mysqli_real_query($con,$sql)){echo "{$dbname}授权给用户成功<br>";}else{echo "{$dbname}授权给用户失败<br>";} $sql="GRANT ALL PRIVILEGES ON `{$dbname}`.* TO `{$username}`@'127.0.0.1'"; if(mysqli_real_query($con,$sql)){echo "{$dbname}授权给用户成功<br>";}else{echo "{$dbname}授权给用户失败<br>";} //刷新权限 盲猜不执行也可以 不过执行了也没啥副作用 mysqli_real_query($con,"FLUSH PRIVILEGES"); //测试连接 if(mysqli_connect('localhost',$username,'密码')){ echo "登录成功<br>"; }else{ echo "登录失败<br>"; } //删除用户 授权的ip要分别删除 删除前要判断用户是不是 root 千万别误把root帐号删了 /* $sql="drop user '要被删除的用户'@'localhost'"; $sql="drop user '要被删除的用户'@'127.0.0.1'"; */