用户登录后如何请求所有用户信息?我想制作一个侧边栏,登录的用户可以在其中看到他存储在数据库中的信息。
只需一个简单的代码就可以了,这样我就可以在任何地方回显信息,例如在 HTML 中:
//WORKS//<?php echo htmlspecialchars($_SESSION['username']); ?>
//NOT WORKING//<?php echo htmlspecialchars($_SESSION['firstname']); ?>
//NOT WORKING//<?php echo htmlspecialchars($_SESSION['lastname']); ?>
//NOT WORKING//<?php echo htmlspecialchars($_SESSION['email']); ?>
数据库:用户 > ID - 用户名 - 名字 - 姓氏 - 电子邮件。
这将是详细信息页面。不要介意HTML。
我的PHP代码
<?php
// Initialize session
session_start();
include("config.php");
// If session variable is not set, redirect to login page
if (!isset($_SESSION['username']) || empty($_SESSION['username'])) {
header("location: login.php");
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Homepagina</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<div class="page-header">
<h1>Hi, <b><?php echo htmlspecialchars($_SESSION['username']); ?></b>. Welcome to our site.</h1>
</div>
<p><a href="logout.php" class="btn btn-danger">Uitloggen!</a></p>
</body>
</html>
// THIS IS THE LOGIN.PHP
if(mysqli_stmt_num_rows($stmt) == 1){
// Bind result variables
mysqli_stmt_bind_result($stmt, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
/* Password is correct, so start a new session and
save the username to the session */
session_start();
$_SESSION['username'] = $username;
$_SESSION['firstname'] = $firstname;
header("location: homepagina.php");
}