简体   繁体   中英

How to fetch a user's id from a database in php?

I am working on a simple PHP web-application. And in that I want to get Id of user from the mysql database.

For that I have used session to store userID as soon as user in inserted in database:

session_start();
$_SESSION['customer_id']=mysqli_insert_id($con); 

But it always says that undefined index customer_id on other pages.It is working fine on localhost but not on live server.

As per the documentation : mysqli_insert_id Returns the auto generated id used in the latest query . If you don't run an insert query before starting session, then mysqli_insert_id will not return what you're looking for.

Rather, try searching for the user with information obtained upon user login, like the user's email address or username.

Eg

SELECT id FROM users WHERE users.username = userSuppliedEmail

It goes without saying that you should use prepared statements or some similar technology for this query.

It looks like something is preventing you from creating a session.

Before you do anything, where you declare session_start , do the following:

Instead of session_start() put:

$started = session_start();
echo "Session Started: " . ($started ? "YES" : "NO");

If PHP says the session is indeed started, make sure the session id is staying the same between requests. You can obtain the session id with:

echo session_id();

From request to request, the session id must be the same, unless it's expired, or deleted. If you get a session id on first page, but no session id on second page, then either session_start wasn't executed, or the session was not created.

Since you assured me session_start is executed, the next thing you need to do is verify that the session is indeed created, and written to a file on the server.

After you obtain the session id, (eg. 7815696ecbf1c96e6894b779456d330e ) you should check your sessions folder for a file named 7815696ecbf1c96e6894b779456d330e (this is just an example, your file name will be different).

$sessionPath = ini_get('session.save_path'); // obtains the path to session
echo "Our session path is: $sessionPath <br/>";
$filesInSessionFolder = scandir($sessionPath); // obtain all files in session folder
if($filesInSessionFolder == false){
    echo "Could not access session folder<br/>";
}else{
    // display all files in the folder
    print_r($filesInSessionFolder);
}

Now make sure that the session id exists in the list.

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