PHP MySQL Foreign Key
What is foreign key
- A column is called foreign key when it refers to the primary key column of another table.
- More than one(multiple) tables can be linked to each other by one or more common fields, called foreign keys.
- foreign keys make it possible to create one-to-one or one-to-many relationships between different tables, and combine data from multiple tables.
Before defining foreign key we have to create Primary key table.
in this example we are creating a table "users" with 4 fields. first field "u_id" is primary key.
How to define Primary key
create table users
(
u_id int primary key auto_increment,
name char(50) not null,
email varchar(50) unique key,
course char(50)
);
Output
How to define foreign key
create table fees
(
fee_id int primary key auto_increment,
paid_fee int not null,
due_fee int not null,
paid_date date not null,
u_id int not null,
foreign key(u_id) references users(u_id)
);
Output
In this example we have create a table "fees" with 5 fields.
in this table "fee_id" is primary key and u_id is
foreign key which refers primary key of first table(users).