如何显示 MySQL 数据库中的特定数据? (获取用户的电子邮件)

How can I display specific data from a MySQL database? (fetching user's email)

我已经用我的帐户页面制作了一个注册系统。

我可以在其中显示名称和密码,但无法在登录后显示电子邮件,因为我必须从 MySQL 数据库中获取它,因为用户在登录时没有输入他的电子邮件。

代码没有错误,但没有显示电子邮件。

这是server.php登录码:

// LOGIN USER 
if (isset($_POST['login_user'])) {
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $password = mysqli_real_escape_string($db, $_POST['password']);

  if (empty($username)) {
   array_push($errors, "Username is required");
  }
  if (empty($password)) {
    array_push($errors, "Password is required");
  }

  if (count($errors) == 0) {
    $password = base64_encode($password);
    $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
    $results = mysqli_query($db, $query);
    if (mysqli_num_rows($results) == 1) {
      $_SESSION['username'] = $username;

//Here is the code with problem

      $query = "SELECT email FROM users WHERE username='$username' AND password=''$password";

      $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        $_SESSION['email'] = $row["email"];
    }
    }

//Here it ends

      $_SESSION['password'] = $password;
      $_SESSION['success'] = "You are now logged in";
      if ($_SESSION['page'] == "account.php"){
          header('location: account.php');
      }
      else{
        header('location: index.php');
      }
    }else {
        array_push($errors, "Wrong username/password combination");
   }
  }
}

登录成功后您应该会收到您的电子邮件。

$password = base64_encode($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);

if (mysqli_num_rows($results) == 1) {
     $row = mysqli_fetch_assoc($result);
     $_SESSION['username'] = $username;
     $_SESSION['email'] = $row['email'];
}

您第二次查询有误,您没有正确引用密码。 也就是说,您根本不需要第二个查询,因为电子邮件字段已经在第一个结果中。你知道它只有一行,因为你检查了 mysqli_num_rows($results) == 1

if (count($errors) == 0) {
    $password = base64_encode($password);
    $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
    $results = mysqli_query($db, $query);
    if (mysqli_num_rows($results) == 1) {
        $user_data = mysqli_fetch_assoc($results);
        $_SESSION['username'] = $username;
        $_SESSION['email'] = $user_data['email'];           
        $_SESSION['password'] = $password;
        $_SESSION['success'] = "You are now logged in";
        if ($_SESSION['page'] == "account.php"){
            header('location: account.php');
        }
        else{
            header('location: index.php');
        }
    }else {
        array_push($errors, "Wrong username/password combination");
    }
}

最后一点,请记住 base64 不是存储密码的理想函数,使用一些哈希函数可能是个好主意。