简体   繁体   English

如何在用户登录时从 PHP 和 MySQL 获取用户 ID、用户名

[英]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.我有这个问题,我无法从数据库中获取用户 ID 和用户名,并在用户登录时将其存储到变量中。(仅适用于电子邮件。)这是我的代码。

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

Delete bindValue rows and try to execute like this删除 bindValue 行并尝试像这样执行

$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在这里查看示例https://www.php.net/manual/en/pdo.prepare.php

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.因此,在您的代码中,当行数为 1 时,您设置了一个 session 变量,表示登录成功。 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.现在变量 $row 将包含您的所有字段,只有这样您才能将值添加到 session 变量,例如用户 ID。 So assuming your user table has "user_id" as the field, you can add code like this:所以假设你的用户表有“user_id”作为字段,你可以添加这样的代码:

if ($num == 1) {
    $row = $query->fetch(PDO::FETCH_ASSOC);
    $_SESSION['user_id'] = $row['user_id'];
    $_SESSION['logged_in'] = true;
    header('Location: index.php');
    exit();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM