简体   繁体   中英

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.

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.

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 
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. How I can get the id for the current logged in user ?

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. You called it in login function, but don't call in 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. Also, probably being pedantic, but you should rename your user variable to $user , $usr makes me wince.

Another way to get session id is: 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 ')")

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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