PHP和MySQL访问级别

I have been trying to add a simple "access" level check, and I can not get it to give me out the value from the Database, I always get Null; even though it is almost the same query as for the User, Pass check.

Anyhow, here is my code, you might be able to get it even a little better done!

*Updated According to Comment

    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;
    }
}

I have got another file called "headerauth.php" it is a little DIV block that has a Welcome $_SESSION['username'] in it that works, and for test/developing reasons a Var_Dump at the end, which gives this result :

array 'username' => string 'test' (length=4)

When I had the Auth in the same block as the userLogin function, the value used to be

Null;

There are at least 3 mistakes in your code:

  • $stmt->bindValue > PDOStatement::bindValue expects the first parameter to be either an integer (for question mark statement parameters) or a string (for named parameters). If you are using named parameters it must begin with a colon! For example $stmt->bindValue(":username", $this->username, PDO::PARAM_STR);

  • session_start($_SESSION) > session_start does not expect any parameters (void)

  • $stmt->bindValue("access", $this->access, PDO::PARAM_INT) > There is no named parameter access in your SQL query
    An exception should be thrown there.

Do you have a custom exception handler / display_errors off / error_reporting off? I do not understand, why no exception is thrown..

Docs: