How to use sessions in PDO?

Posted by Byakugan on Stack Overflow See other posts from Stack Overflow or by Byakugan
Published on 2012-06-09T15:44:47Z Indexed on 2012/06/09 16:40 UTC
Read the original article Hit count: 328

Filed under:
|
|
|

I am still redoing and getting rid of old mysql_* commands in my code. I tried to transfer my session login form old code and this is what I got so far:

  public function login($user, $password)
  {
    if (!empty($user) && !empty($password))
    {    
      $password = $web->doHash($user, $password); // in this function is (return sha1(strtoupper($user).':'.strtoupper($password))
      $stmt = $db_login->prepare("SELECT * FROM account WHERE username=:user AND pass_hash=:password");
      $stmt->bindValue(':user', $user, PDO::PARAM_STR);
      $stmt->bindValue(':password', $password, PDO::PARAM_STR);
      $stmt->execute();
      $rows = $stmt->rowCount();

      if ($rows > 0)      
      {    
        $results_login = $stmt->fetch(PDO::FETCH_ASSOC);
        $_SESSION['user_name'] = $results_login['username'];
        $_SESSION['user_id'] = $results_login['id'];  
        return true;
      }
      else
      {
        return false;
      }
    }
    else
    {
      return false;
    }
  }

After that I am using checks if user logged on site:

  public function isLogged()
  {
    return (!empty($_SESSION['user_id']) && !empty($_SESSION['user_name']));
  }

But it seems - this function returns always empty because $_SESSION does not exists in PDO? And of course logout is used in this form on my sites:

  public function logout()
  { 
      unset($_SESSION['user_id']);
      unset($_SESSION['user_name']);       
  } 

But I think PDO has different way of handling session? I did not find any so what is it can i somehow add $_SESSION in PDO withou changing code much?

I am using variables $_SESSION['user_name'] and $_SESSION['user_id'] in all over my web project.

Summary:

1) How to use sessions in PDO correctly?

2) What is difference between using $stmt->fetch(PDO::FETCH_ASSOC); and $stmt->fetchAll();

Thank you.

© Stack Overflow or respective owner

Related posts about php

Related posts about session