我已经从教程中设置了登录/注册系统,现在我正在尝试使用会话来显示个人资料信息。我看了很多论坛和教程,我相信我有实际的代码来显示数据库中的实际信息,但我不能让它显示。我可能做错了什么......我正在尝试从数据库中获取“电子邮件”部分,并将其显示在配置文件中。
<?php
require('db.php');
// Create connection
$conn = new mysqli("XXXXXX");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, username, email FROM users";
$result = $conn->query($sql);
$_SESSION['email'] = $_POST['email'];
?>
<?php
session_start();
?>
<p><strong>Email:</strong> <?php echo $_SESSION['email']; ?></p>
答案 0 :(得分:2)
从我能想到的有限信息中可以看出:
在这种情况下,这是您的情况的基本假设:
首先,如果您在登录后将用户转移到此页面,则表示没有$ _POST数据(通常)。你可以使用var_dump($ _ POST)确认它。
您在登录时已在某处设置了$ _SESSION变量。我们假设它是$ _SESSION [&#39; email&#39;],您可以使用var_dump($ _ SESSION)确认它。
基于这个假设,这是修改后的代码的样子:
<?php
require('db.php');
//This should come first before accessing $_SESSION
session_start();
// Create connection
$conn = new mysqli("XXXXXX");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//This query should be used with WHERE as you only want to get data of one particular user.
//This is just for an example purpose, in practice you should always use parameterized query Or at least escape data before using it.
$sql = "SELECT id, username, email FROM users WHERE email = " . $_SESSION['email'] . ";";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
//Assuming only one record will be returned because username/email should be unique
$result = $row;
}
} else {
//Handle if you don't get any data
}
$email = $result['email'];
?>
<p><strong>Email:</strong> <?php echo $email; ?></p>
我希望这可能会有所帮助