我在我的项目中使用核心 php 和 mysql。我陷入了 session 部分。我无法理解如何为用户名创建 session 以在登录后显示他的名字。我尝试了很多次但都失败了。请帮助我。下面是我的 insertUser.php 代码。其中总共有 3 个登录查询。我正在处理 super 管理员的第二个查询。正如您在我的代码中注意到的那样,我为 super 管理员的用户名创建了 session 。我在 home.php 中包含了 menubar.php 、 header.php 和 sidebar.php 。我想在menubar.php和header.php中添加 session 。
插入用户.php
<?php
include 'db.php';
if (isset($_REQUEST['insert']))
{
$acc_name = $_REQUEST['username'];
$acc_email = $_REQUEST['email'];
$acc_pass = $_REQUEST['password'];
$role_id = $_REQUEST['roleid'];
$sql = mysqli_query($conn,"INSERT INTO `accountants`(`acc_name`, `acc_email`, `acc_pass`, `roleId`) VALUES ('".$acc_name."','".$acc_email."','".$acc_pass."','2')");
if ($sql>0)
{
header('Location: home.php');
echo 'data added successfully';
}
$row = mysqli_query('SELECT * FROM `accountants`');
$data = mysqli_fetch_array($row);
$data = mysqli_num_rows($conn,$data);
$_SESSION['role'] = $data['roleId'];
}
if (isset($_REQUEST['submit']))
{
$username = $_REQUEST['user'];
$password = $_REQUEST['pass'];
$sql = mysqli_query($conn,"SELECT * FROM `accountants` where `acc_email` = '".$username."' AND `acc_pass` = '".$password."'");
$data = mysqli_fetch_array($sql);
$_SESSION['role']=$data['roleId'];
$_SESSION['username']=$data['acc_name'];
$sql1 = mysqli_query($conn,"SELECT * FROM `superadmin` where `username` = '".$username."' AND `password` = '".$password."'");
$data02 = mysqli_fetch_array($sql1);
$_SESSION['role']=$data02['roleId'];
$sql2 = mysqli_query($conn,"SELECT * FROM `member` where `email` = '".$username."' AND `password` = '".$password."'");
$data01 = mysqli_fetch_array($sql2);
$_SESSION['role']=$data01['roleId'];
$_SESSION['username']=$data01['fname'];
if ($data01>0)
{
header('Location: DigitalSociety - Member/production/societyList.php');
}
elseif ($data>0)
{
header('Location: societyList.php');
}
elseif ($data02>0) {
$_SESSION['login_user']=$username;
header('Location: DigitalSociety - Superadmin/production/societyList.php');
}
else
{
header('Location: index.php');
echo 'incorrect login';
}
}
?>
菜单栏.php
<div class="profile clearfix">
<div class="profile_pic">
<img src="images/img.jpg" alt="..." class="img-circle profile_img">
</div>
<div class="profile_info">
<span>Welcome,</span>
<h2><?php echo $_SESSION['login_user'];?></h2>
</div>
</div>
我使用上面的代码来显示用户名,它显示错误 Undefined variable: _SESSION in
请帮助我。
最佳答案
您的文件顶部缺少 session_start();
。
关于php - 如何在php中创建用户名 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43693251/