我正在尝试创建自己的自定义CMS,我可以注册用户并可以登录aswel,现在我正在尝试为用户角色创建一个函数,
文件:class.user.php
function getUserrole() {
$username = htmlentities($_SESSION['user_session']);
$stmt = $this->db->prepare('SELECT * FROM users WHERE user_name = :username');
$stmt->bindParam(':user_name', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$userrole = $row['user_role'];
if($userrole == 3) {
return $userrole = 3;
}
if($userrole == 2) {
return $userrole = 2;
}
if($userrole == 1) {
return $userrole = 1;
}
if($userrole == 0) {
return $userrole = 0;
}
}
文件:Home.php
<?php
$userrole = getUserrole();
if($userrole == 1) {
echo "Hi Admin";
}
else {
echo "You are not a admin";
}
?>
当我尝试这样做时,错误显示出来:
Fatal error: Call to undefined function getUserrole() in /Applications/MAMP/htdocs/test/home.php on line 24
我可以看到一些错误,我希望你们能帮助我在这里:)
整个class.user.php:
<?php
class USER
{
private $db;
function __construct($DB_con)
{
$this->db = $DB_con;
}
public function register($uname,$umail,$upass)
{
try
{
$new_password = password_hash($upass, PASSWORD_DEFAULT);
$stmt = $this->db->prepare("INSERT INTO users(user_name,user_email,user_pass)
VALUES(:uname, :umail, :upass)");
$stmt->bindparam(":uname", $uname);
$stmt->bindparam(":umail", $umail);
$stmt->bindparam(":upass", $new_password);
$stmt->execute();
return $stmt;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function login($uname,$umail,$upass)
{
try
{
$stmt = $this->db->prepare("SELECT * FROM users WHERE user_name=:uname OR user_email=:umail LIMIT 1");
$stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
if(password_verify($upass, $userRow['user_pass']))
{
$_SESSION['user_session'] = $userRow['user_id'];
return true;
}
else
{
return false;
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function is_loggedin()
{
if(isset($_SESSION['user_session']))
{
return true;
}
}
public function redirect($url)
{
header("Location: $url");
}
public function logout()
{
session_destroy();
unset($_SESSION['user_session']);
return true;
}
function getUserrole() {
$username = htmlentities($_SESSION['user_session']);
$stmt = $this->db->prepare('SELECT * FROM users WHERE user_name = :username');
$stmt->bindParam(':user_name', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$userrole = $row['user_role'];
if($userrole == 3) {
return $userrole = 3;
}
if($userrole == 2) {
return $userrole = 2;
}
if($userrole == 1) {
return $userrole = 1;
}
if($userrole == 0) {
return $userrole = 0;
}
}
}
?>
答案 0 :(得分:0)
要求home.php中的类,init,然后调用函数
<?php
require_once 'class.user.php';
$userClass = new USER(<yourdbcon>);
$userrole = $userClass->getUserrole();
if($userrole == 1) {
echo "Hi Admin";
}
else {
echo "You are not a admin";
}
&GT;