简体   繁体   English

如何从会话中获取$ _SESSION ['id']

[英]How to get $_SESSION['id'] from a session

Hello I have 2 tables in my database one for courses and one for users, each of them has an id column. 您好,我的数据库中有2个表,一个表用于课程,一个表用于用户,每个表都有一个id列。

I am trying to create a relationship between them, one user subscribe to one course. 我正在尝试在他们之间建立关系,一个用户订阅了一个课程。 The result I am trying to store inside a 3rd table called subscription, which has a column for the course ID and column for user id. 我试图将结果存储在称为订阅的第3个表中,该表具有一列用于课程ID和一列用于用户ID。

The users are registering after passing log-in which is connected with a new session. 用户通过与新会话相关的登录后正在注册。 After user click subscribe link which is 用户单击后,订阅链接是

<a href='subscribe.php?id=".$row['id']."'>subscribe!</a>

they are taken to the backend php page where it is the inserted into database information: 它们被带到后端php页面,在该页面中已将其插入数据库信息中:

<?php 
session_start();

?>
   $userid = $_SESSION['userID'];    
   $cursoid = $_GET['id'];

    mysql_connect("localhost", "username", "password") or die(mysql_error()) ; 
    mysql_select_db("test") or die(mysql_error()) ; 


    mysql_query("INSERT INTO `subscriptions` 
                     (curso_id, user_id) 
                     VALUES ('$cursoid', '$userid ')")
                         or die(mysql_error()); 

at this point I have obtained the id of the course and it is inserted inside it, the problem is for the user ID I am not getting anything. 至此,我已经获得了课程的ID,并将其插入课程中,问题是用户ID我什么都没得到。 How I can get the id for the current logged in user ? 如何获取当前登录用户的ID?

here is the code of my class for the login function: 这是我的登录函数类的代码:

    public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();

$valid = $stmt->fetchColumn();

if( $valid ) {
$success = true;

}


$con = null;
return $success;
}catch (PDOException $e) {
echo $e->getMessage();
return $success;

$user = $stmt->fetchObj();

    if( $user->user_id > 0 ) {

        $success = true;

        // User has been successfully verified, lets sessionize his user id so we can refer to later
        $_SESSION['userID'] = $user->user_id;}

}
}

and finally here is the code of the login function: 最后是登录功能的代码:

session_start();
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
    header( 'Location: cursos.php' ) ;
    $_SESSION["loggedIn"] = true;
    $_SESSION['username'] = $_POST['username'];
    $_SESSION['password'] = $_POST['password'];
    $_SESSION['id'] = $_POST['id'];

Every time you want to work with a session, you must call session_start function at the beginning of the file. 每次要使用会话时,都必须在文件开头调用session_start函数。 You called it in login function, but don't call in subscribe.php. 您在登录功能中调用了它,但不要在subscribe.php中调用它。 Try this: 尝试这个:

session_start();

$userid = $_SESSION['id'];
$cursoid = $_GET['id'];
//rest of the code

You should NOT be using sessionIds as userIds, instead you should be using the primary key of the user table after you have inserted the user row. 您不应将sessionIds用作userIds,而应在插入用户行之后使用user表的主键。 Also, probably being pedantic, but you should rename your user variable to $user , $usr makes me wince. 另外,可能是很古怪的,但是您应该将用户变量重命名为$user$usr使我畏缩。

Another way to get session id is: session_id 获取会话ID的另一种方法是: session_id

-- Edit -- -编辑-

public function userLogin() {

    ....

    $user = $stmt->fetchObj();

    if( $user->user_id > 0 ) {

        $success = true;

        // User has been successfully verified, lets sessionize his user id so we can refer to later
        $_SESSION['userId'] = $user->user_id;
    }
}

// We sessionized user id after validation, so we now have access to it
$userid = $_SESSION['userId'];

// Using straight mysql api is frowned upon, this should be converted to PDO before production use
mysql_query("INSERT INTO `subscriptions` (curso_id, user_id) VALUES ('$cursoid', '$userid ')")
    or die(mysql_error()); 

Also you have a minor error here as well, you had a space in this line VALUES ('$cursoid', '$userid ')") 另外,您在这里也有一个小错误,在此行VALUES ('$cursoid', '$userid ')")有一个空格

mysql_query("INSERT INTO `subscriptions` 
             (curso_id, user_id) 
             VALUES ('$cursoid', '$userid')")
                 or die(mysql_error()); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM