简体   繁体   中英

Getting all info of the logged in user? PHP

HI

Could I fetch ALL the info from the user when he/she login and store it in sessions instead of having this piece of code on top of all pages to get username, email etc of the logged in user?

$userq = mysql_query("SELECT * FROM users WHERE id = {$_SESSION['id']}");
$auth_user = mysql_fetch_assoc($userq);

Login.PHP

$sql = mysql_query("SELECT id FROM users 
                       WHERE username = '$username' AND password = '$password'");

if (mysql_num_rows($sql) < 1) {
    echo "Wrong username/password";
} else {
    $_SESSION['id'] = mysql_result($result, 0, 'id');
    header("Location: index.php");  
}

Yes you (probably) could.

A couple of things to consider, though :

  • you might want to keep in session only what you need (to not have a giant session file with lots of useless data)
  • if the user updates his profile, you'll have to store the new data both in database, and in session -- which means a bit more works on the "edit profile" page.
  • if some other user (like an admin) edits a user's profile, you won't be able to change the session data of that user, and the updates will be loaded from database into the session only the next time the user logs in.
    • if this is something that happens frequently, you might want to refresh the data from databse every couple of minutes (but it's rarely the case on a "normal" website)

yeah, instead of getting just the id in the query, you get everything:

$sql = mysql_query("SELECT * FROM users 
                   WHERE username = '$username' AND password = '$password'");

if (mysql_num_rows($sql) < 1) {
    echo "Wrong username/password";
} else {
    $_SESSION['userdata'] = mysql_result($result, 0);
    header("Location: index.php");  
}

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