Reputation: 37
i am trying to add few things to session when user log in. For example user_level, or id.
So my code looks like this:
public function userLogin() {
$success = false;
try{
$con = new PDO( DB_HOST, DB_USER, DB_PASS );
$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->execute();
$valid = $stmt->fetchColumn();
$_SESSION['username'] = $this->username;
$_SESSION['id'] = $stmt->fetchColumn(1);
if( $valid ) {
$success = true;
}
$con = null;
return $success;
}catch (PDOException $e) {
echo $e->getMessage();
return $success;
}
So as u can see i am adding username and trying to add id as well. Username works fine but as soon as i take id from database i have some problem there. Its not stored, actualy if i var_dump it it says bool(false)
Can somebody tell me what i am doing wrong? Or gimme some advise. I also wonder if this is secure to store things like user level and id in session to limit access for some part of website.
Upvotes: 0
Views: 81
Reputation: 21004
instead of
$_SESSION['id'] = $stmt->fetchColumn(1);
considering your id column is named id, use
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC)
$_SESSION['id'] = $rows[0]['id'];
Directly from PHP docs :
fetchColumn returns a single column from the next row of a result set or FALSE if there are no more rows.
Upvotes: 1