Best unofficial Apache Server developers community
Username
Forgot password?
Sign in with Twitter account
Sign in with Facebook account

How to connect the users table to the roles table (using the table user_roles)?

0

45 views

I need to create a basic database for user authentication. So far, every user has a name, a password and a role. I've found this somewhere on the Internet, which looks quite promising:

create table if not exists users (
  id int unsigned not null auto_increment,
  username varchar(100) not null,
  password binary(60) not null,
  primary key(id),
  unique(username)
);

create table if not exists roles (
  id int unsigned not null auto_increment,
  role varchar(100) not null,
  primary key(id),
  unique(role)
);

create table if not exists user_roles (
  user_id int unsigned not null,
  role_id int unsigned not null,
  unique(user_id, role_id),
  index(user_id)
);

But... if I would create new users, how would I fill the user_roles table? I have a feeling there is some "automatic way" to do this, but I have totally no idea (being a database noob :-)). How could I somehow connect a user to a role?

asked June 20, 2011 4:14 pm CDT
posted via StackOverflow

2 Answers

0
 

For each user, you simply insert one row in the user_roles table for every role you want to assign to that given user. There's nothing automatic about it. It's a many-to-many relationship.

answered June 20, 2011 4:23 pm CDT
1
Best answer
 

You would first populate the roles table. Then, add a user to the users table. Then, taking the ID from the users table, you want to associate it with an ID from the roles table inside of the user_roles table. Like so:

---- Users Table ---------
ID | UserName | Password
 1 | Test     | *****
--------------------------

---- Roles Table ---------
ID | Role
 1 | Test_Role
 2 | Another_Role
--------------------------

---- User Roles Table ---------
UserID | RoleID
     1 |      1
     1 |      2
-------------------------------

This is done for a "Many To Many" relationship. It's also called "Normalizing" your database.

answered June 25, 2011 6:45 am CDT

Your answer

Join with account you already have


Sign in with Twitter account
Sign in with Facebook account
Sign in with Google Friend Connect

Preview
Similar questions