简体   繁体   中英

How to handle selecting a database based on the user?

I am building a website that will have multiple users from multiple companies. Each company is given a copy of the same database with the same tables. The only difference is the database name. I would like for each user to only have access to the database assigned to their company.

I need to come up with a way to select the database based on the user's login. Is it acceptable to use a session var from a users table as the database name?...

$dbCon = new mysqli('localhost', 'root', '', $_SESSION['databaseName']);

Maybe a cookie? Or am I looking at the whole thing wrong. Any input would be great. I'm still learning. Thanks

My suggestion is to pick one database as your "login" database that has all the user accounts in a table. Then add a column to the user table that you are authenticating their login against. You can store the company or "assigned database name" in that column. Once authenticated you can close your DB connection and open up a new connection with the correct assigned database.

You can have following schema for you user login

LoginTable : (username,password,...,company_id)

Company : (company_id,....,dbname)

So as soon as user login he can select the database corresponding the company id from the company table. The query can be written in a single command by natural joining company and LoginTable.Hence after retrieving the dbname you can store it in session variable for further use.

I hope you understood.

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