I don't know how to transfer user_id to the next page in php

I tried to create a login page in which unauthorized people will be unable to access the protected page in php and I tried to protect the pages using this php code<?php if(!isset($_SESSION)){ header ("Location: admin_login.php"); ?>. But the problem is if I include the above code into the pages, it will always return me to the login page but if I comment the code out, I will be able to login successfully with the infomations from the database, even though, when creating the php code for searching for the user from the database I also ask the PHP code bring along it with the id and this is the code<?php $query ="SELECT email, password, id FROM author WHERE email = '{$email}' AND password = '{$password}' AND id" then I tried to pass it into the SESSION like this $_SESSION['email'] = $email; $_SESSION['password'] = $password; $_SESSION['id'] = $id. Yet, I don’t know why its not working, please who can put me through. Thanks in advance.

You have

session_start();

at the top of all your pages?
I would also look for a specific KEY like id.

<?php
session_start();
if(!isset($_SESSION['id'])){ 
header ("Location: admin_login.php"); 
exit;
}
?>

Please DO NOT save a persons login information to session. Use an [‘id’] or [‘level’] = “admin” etc.

I think you mean

session_start();

I know and that is what I did, but the problem is I can’t figure out. I just echoed all the username, password and id on another page using session. okay, lets put it like this…how do I get the id of the username from the database and pass it into session. I think, the problem is this, since I get the email and password from the form and comparing it with the one in database but there is no way (from my point of view) I can get the id from the database…how do I get it from the database.

Ha, Ya I think I’m starting to loose it. Getting old… :smile:
Edited post above.

If you are trying to retrieve data from your database using a session variable, you need to establish a connection first. Do NOT use the old MySQL_* extensions for this has been deprecated in the newer versions and will probably be removed in the future.

This is just a sample code. This is not your actual data. It’s to show you how you should be going about it.

MySQLi version

<?php
session_start(); // Always put this in front of every page if you want to use sessions
define('DB_HOST', 'localhost'); // Your actual mysql hosting server
define('DB_USER', 'username'); // Your actual mysql username
define('DB_PASS', 'password'); // Your actual mysql password. NOTE: No one will actually see this except you
define('DB_DATA', 'database'); // Your actual mysql database.

// Check to see if the session "username" exsts
if(isset($_SESSION['username'])) {

         $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DATA);
         if($mysqli->connect_error) {

                 // Do not actually print your errors on screen, this is a bad idea. Anyone can see it and access your files.
                // Suggestion is to turn error logging on and to send it to your default error logs

         }

         // We're going to be using prepared statements because it's good practice
         $select = $mysqli->prepare("SELECT id, username FROM users WHERE username = ? LIMIT 1");
         $select->bind_param("s", $session_username); // Bind the place holder to avoid SQL Injection
         $session_username = $_SESSION['username']; // Needs this to define what we are trying to bind
         $select->execute(); // Execute the prepare statement
         $select->store_result(); // Use store result so we can use it later

         // Check to see if the username actually exists, if it does not. Do not display it
         if($select->num_rows) {

                 $select->bind_result($user_id, $username); // This acts like $row['id'], $row['username']

                 // Loop it in a while loop
                 while($select->fetch()) {

                         // Your custom messages
                         echo "This is your ID: " . $user_id . "<br />";
                         echo "This is your username: " . $username;

                  }

          } else {

                  echo "The username doesn't exists. Maybe the session was modified";

           }

} else {

        echo "Session username was not set";

}

PDO Version

<?php
session_start(); // Always put this in front of every page if you want to use sessions
define('DB_HOST', 'localhost'); // Your actual mysql hosting server
define('DB_USER', 'username'); // Your actual mysql username
define('DB_PASS', 'password'); // Your actual mysql password. NOTE: No one will actually see this except you
define('DB_DATA', 'database'); // Your actual mysql database.

// Check to see if the session "username" exsts
if(isset($_SESSION['username'])) {

    // PDO equivalent of connect_error
    try {
        $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_DATA . "", DB_USER, DB_PASS);
    } catch (PDOException $e) {
        exit('Database connection could not be established.');
    }

    // We're going to be using prepared statements because it's good practice
    $sql = "SELECT id, username FROM users WHERE username = :username LIMIT 1";
    $select = $pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
    $session_username = $_SESSION['username']; // Needs this to define what we are trying to bind
    $select->execute(array(':username' => $session_username)); // Execute the prepare statement

    // Check to see if the username actually exists, if it does not. Do not display it
    // PDO equivalent of num_rows
    if($select->rowCount()) {

        // Loop it in a while loop
        while($row = $select->fetch()) {

            // Your custom messages
            echo "This is your ID: " . $row['id'] . "<br />";
            echo "This is your username: " . $row['username'];

        }

    } else {

        echo "The username doesn't exists. Maybe the session was modified";

    }

} else {

    echo "Session username was not set";

}

In both of these samples, you see that I try to find if the username doesn’t exist. The reason why I believe you should do that is because if the username doesn’t exist and you are trying to fetch it from the database, although you don’t receive on screen errors or errors in your error log, I believe this is not a good thing. What if a user happens to not actually exist such as what if they deleted their account and never got logged off properly? Should the user be blamed for doing that if your code doesn’t check to see if the username actually exists?

Next, properly checking to see if the user has the right credentials or they can bypass this whole step.

These are samples for you to use if you get stuck. I’m not going to say that your actual codes are going to look like this, it’s just something for you to look at in case you get stuck some where in your codes.

Note: You should be using prepared statements when you are accepting user inputs. I’m not sure if this falls under the lines, but it’s best practice to use prepared statements when you can. Especially if you are doing a WHERE clause.

Use a key, as suggested. For example:

if(!isset($_SESSION['logged'] || $_SESSION['logged'] != true))

You should use some kind of generic key like this.

On your actual log in page, you will be submitting the form to a parsing script of some sort to check for the user. You gave this code:

$query ="SELECT email, password, id FROM author WHERE email = '{$email}' AND password = '{$password}' AND id

I don’t know where the “AND id” comes from, you don’t need that. You are selecting email, password, and id where email and password match, so more like this:

SELECT email, password, id FROM author WHERE email = '{$email}' AND password = '{$password}' LIMIT 1

This will give you a result with those 3 items in your return object. If nothing is found, of course you will report to the user that no user was found.

When you find a user successfully, you must immediately set your session variables:

// Successfully found user
$_SESSION['logged'] = true;
$_SESSION['id'] = $result['id']; // use query result by whatever method
$_SESSION['username'] = $result['username'];

Then redirect the user to the “logged in” page or what have you.

As long as you are running session_start(); at the start of your pages, it will reconnect the session and your variables will be available.

Sessions cannot be started if PHP has sent ANY response whatsoever. Don’t echo anything or do anything that produces output or the session won’t start properly.
Another reason it could break is if your cookies are blocked or somehow your browser is not allowing any sort of session storage, which is uncommon.

Also remember, you have the $email and $password variables from the form, but you get the ID from the database query, so you have to access it through the return result of the query by converting the result to an array for example.

And as a reminder, make sure your email and password are properly sanitized! Hence prepared statements.

I know that I shouldn’t echo the session but I want to know why is not working, that is why I did that. I will also try what you suggested

Thanks so much, but I still use mysqli procedural statements as am a beginner. after this, I will move to oop

There is almost no difference between the two ways of calling so you might as well use oop from the start.

Simply change from

mysqli_query($db, $sql)

to

$db->query($sql)

and similarly for all the other calls apart from the call at the start to connect to the database

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.