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

Time:04-26

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

CodePudding user response:

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

CodePudding user response:

Delete bindValue rows and try to execute like this

$query=$pdo->prepare('SELECT * FROM user WHERE email = ? AND password = ? ');
$query->execute([$email, $password]);

Look at examples here https://www.php.net/manual/en/pdo.prepare.php

  • Related