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?
You would first populate the
rolestable. Then, add a user to theuserstable. Then, taking the ID from theuserstable, you want to associate it with an ID from therolestable inside of theuser_rolestable. Like so:This is done for a “Many To Many” relationship. It’s also called “Normalizing” your database.