通过会话登录用户的详细信息

时间:2016-12-06 05:27:19

标签: php mysql session

我想创建一个表,每个用户/组只能看到他们的数据。

所以我让每个用户/组在用户表中都有他们的用户类型号

+---------+----------+------------------------------------------+----------+
| User_id | username | pwd                                      | usertype |
+---------+----------+------------------------------------------+----------+
通过会话获取当前登录用户的usertype,我想对主数据表进行以下查询。

例如,如果usertype的值为1,则可以看到具有此查询的表(SELECT * FROM table WHERE usertype ='1')

这是我的loginsubmit.php,其中提交并启动会话

<?php
require_once('php_action/db_connect.php');
session_start();

if(isset($_SESSION['user_id'] ))
{
    $message = 'User is already logged in';
}
if(!isset( $_POST['username'], $_POST['pwd']))
{
    $message = 'Please enter a valid username and password';
} 
else if (strlen( $_POST['username']) > 20 || strlen($_POST['username']) < 4)
{
    $message = 'Incorrect Length for Username';
}
else if (strlen( $_POST['pwd']) > 20 || strlen($_POST['pwd']) < 4)
{
    $message = 'Incorrect Length for Password';
}
else if (ctype_alnum($_POST['username']) != true)
{
    $message = "Username must be alpha numeric";
}
else {
    $username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
    $pwd = filter_var($_POST['pwd'], FILTER_SANITIZE_STRING);
    $pwd = sha1( $pwd );
    
    try {
       
        $sql = "SELECT User_ID FROM User_Dfn WHERE username = '".$username."' AND pwd = '".$pwd."'";
    
        if($result=mysqli_query($connect,$sql)) {
            while($row=mysqli_fetch_assoc($result)) {
                $user_id = $row['User_ID'];
                $usertype = $row['usertype'];
                $_SESSION['user_id'] = $user_id;
                $_SESSION['usertype'] = $usertype;
                $_SESSION['timeout'] = time();
                
                header("Location: index.php");
                
            }
        }
        
        if($user_id == false);
        {
            $message ='Login Failed';
            
            
        }
    } catch(Exception $e) { $message = 'Unable to process request'; }
}
?>

这是一个php文件的片段,用于检索数据。

    <?php 

require_once 'db_connect.php';
$usertype= $_SESSION['usertype'];

$output = array('data' => array());

$sql = "SELECT * FROM Service WHERE user_id = '$usertype'";
$query = $connect->query($sql);

好吧,我希望你能理解我想解释的内容,这对我来说有点复杂..

它只是不将usertype加载到sqlquery中。我想我做错了什么

请帮忙

谢谢

2 个答案:

答案 0 :(得分:0)

您尚未在检索文件中调用session_start();

答案 1 :(得分:0)

这会奏效。

<?php 

require_once 'db_connect.php';
session_start();
$usertype= $_SESSION['usertype'];

$output = array('data' => array());

$sql = "SELECT * FROM Service WHERE user_id = '$usertype'";
$query = $connect->query($sql);

?>

请参阅此documentation