我一直在尝试添加一个简单的“访问”级别检查,但我无法让它从数据库中给出值,我总是得到 Null;即使它与用户的查询几乎相同,但通过检查。
无论如何,这是我的代码,你也许可以做得更好!
*根据评论更新
public function userLogin() {
$success = false;
try {
$con = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";
$stmt = $con->prepare($sql);
$stmt->bindValue(":username", $this->username, PDO::PARAM_STR);
$stmt->bindValue(":password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR);
// $stmt->bindValue("access", $this->access, PDO::PARAM_INT);
$stmt->execute();
$valid = $stmt->fetchColumn();
if ($valid) {
$success = true;
session_start();
$_SESSION['username'] = $this->username;
}
$con = null;
return $success;
} catch (PDOException $e) {
echo $e->getMessage();
return $success;
}
}
public function auth() {
$con = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT access FROM users WHERE access = :1 OR access = :2";
$stmt = $con->prepare($sql);
$stmt->bindValue(":access", $this->access, PDO::PARAM_INT);
$stmt->execute();
$access = $stmt->fetchColumn();
if ($access == 1) {
session_start();
$_SESSION['isAdmin'] = $this->access;
} if ($access == 2) {
session_start();
$_SESSION['isUser'] = $this->access;
}
}
我有另一个名为“headerauth.php”的文件,它是一个小 DIV 块,其中有一个 Welcome $_SESSION['username'] 可以工作,并且出于测试/开发原因,最后有一个 Var_Dump,它给出了这个结果:
数组“用户名”=> 字符串“测试”(长度=4)
当我将 Auth 与 userLogin 函数放在同一个块中时,该值曾经是
无效的;