简体   繁体   中英

Translating user_id from one table in sql to another table

I have a database with a "session" table, a "log" table and a "users" table(among others). The user_id in the "log" and "session" tables is a number. This number shows up in the users table under user_id(it generates a random number when a new user is created).

Each time a user logs in, a row is added to both the "session" and "log" tables with that number as the user_id. I'd like to make it so that when a user logs in, his actual username gets written to the database, not the number. Somehow I'd like it to look up that user_id number in the "users" table and translate it to the username in the "users" table and write it to the "sessions" and "log" tables.

Maybe add some code to my session_util.php file to accomplish this? I really hope this all makes sense to someone.

It would be easier if we could see your schemas, but the queries you are looking for are something like the following:

To get the username by id:

"SELECT username FROM users WHERE user_id='" + id + "';"

That query should get you the username, which you can assign to a local variable for use in your insert statements. In your insert statements, change the user_id to username (you will need to alter your schema assuming that user_id is an int and username is a varchar).

I would suggest to you to continue using the user_id for the identifier though, since it is an id it should be guaranteed that it is a unique identifier. You can then use the sql statement above to turn this id into a username and use that where you need it.

Need some more info. First, What are your table attributes (you'll need a user name column in both the log and session tables to start with) and are you using OOP?

Why would you want to have the user name instead of the id ? Why not convert the id to the name when you are outputting the data and keep the id number in the tables?

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