Skip to content
Advertisement

How to get user ID, username from PHP and MySQL while user is logged in

I have this issue where I can’t get user ID and username from database and store it into variable while user is logged in.(Only works with e-mail.) This is my code.

<?php
    if (isset($_POST['email'], $_POST['password'])) {
      $email = $_POST['email'];
      $password = md5($_POST['password']);
      if (empty($email) or empty($password)) {
        $error = 'All fields are requred!';
      }
      else {
        $query=$pdo->prepare('SELECT * FROM user WHERE email = ? AND password = ? ');
        $query->bindValue(1, $email);
        $query->bindValue(2, $password);
        $_SESSION['email']=$email;
        $query->execute();
        $num=$query->rowCount();
        if ($num == 1) {
          $_SESSION['logged_in'] = true;
          header('Location: index.php');
          exit();
        }
        else {
          $error = 'Incorrect data';
        }
      }
    }
  }
?>

Advertisement

Answer

You are calling the “execute” method of prepared statement but nowhere you are calling the “fetch” method. So in your code when you get rowcount as 1, you are setting a session variable indicating successful login. There you need to add following code:

$row = $query->fetch(PDO::FETCH_ASSOC);

Now the the variable $row will have all your fields and only then you can add values to session variables like user id. So assuming your user table has “user_id” as the field, you can add code like this:

if ($num == 1) {
    $row = $query->fetch(PDO::FETCH_ASSOC);
    $_SESSION['user_id'] = $row['user_id'];
    $_SESSION['logged_in'] = true;
    header('Location: index.php');
    exit();
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement