<?php
session_start();
if(isset($_POST['submit'])) {
include('CONFIG/config.php');
include('CONFIG/db.php');
$Email = $_POST['email'];
$Password = $_POST['password'];
$_SESSION['email'] = $Email;
//erroe handler
//check if the input is empty
if(empty($Email) || empty($Password)) {
header("Location: ../index.php?login=error");
exit();
}else{
$sql = "SELECT * from users where email='$Email' AND password='$Password'";
$sql2 = "SELECT roles.id from users, roles where users.email='$Email' and roles.id = users.role_id";
$result2 = mysqli_query($conn, $sql2);
$result = mysqli_query($conn, $sql);
$_SESSION['roleid'] = $result2;
$resultCheck = mysqli_num_rows($result);
if($resultCheck < 1){
header("Location: ../index.php?login=error");
exit();
}else{
header("Location: ../dashboard.php?login=success");
exit();
}
}
}else{
header("Location: ../index.php?login=error");
exit();
}
表结构:角色
1 idPrimary int(11) No None AUTO_INCREMENT
2 title varchar(150) utf8_unicode_ci No None
表结构:用户
1 idPrimary int(11) No None AUTO_INCREMENT
2 name varchar(150) utf8_unicode_ci No None
3 email varchar(150) utf8_unicode_ci No None
4 password varchar(256) utf8_unicode_ci No None
5 role_id int(11) No None
当我运行这段代码并打印会话时,像这样打印$ _SESSION ['roleid'] [roleid] => mysqli_result对象([current_field] => [field_count] => [lengths] => [num_rows] => [type] =>),但我想要的结果是1
答案 0 :(得分:2)
您需要从$result2
获取结果。另外,将$_SESSION['roleid']
移至成功部分。因为您只需要为成功登录设置会话。查看更新的代码。
<?php
session_start();
if (isset($_POST['submit'])) {
include('CONFIG/config.php');
include('CONFIG/db.php');
$Email = $_POST['email'];
$Password = $_POST['password'];
$_SESSION['email'] = $Email;
//erroe handler
//check if the input is empty
if (empty($Email) || empty($Password)) {
header("Location: ../index.php?login=error");
exit();
} else {
$sql = "SELECT * from users where email='$Email' AND password='$Password'";
$sql2 = "SELECT roles.id from users, roles where users.email='$Email' and roles.id = users.role_id";
$result2 = mysqli_query($conn, $sql2);
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck < 1) {
header("Location: ../index.php?login=error");
exit();
} else {
$row = mysqli_fetch_array($result2,MYSQLI_ASSOC); // Fetch the result
$_SESSION['roleid'] = $row['id']; //Set the id to the session variable
header("Location: ../dashboard.php?login=success");
exit();
}
}
} else {
header("Location: ../index.php?login=error");
exit();
}
请参见mysqli_fetch_array()函数