How to Create a Foreign Key in PHPmyadmin

In the world of database management, foreign keys play a crucial role in maintaining data integrity and relationships between tables.

In this tutorial, we will walk you through the process of creating a foreign key in PHPmyAdmin, a popular web-based tool for managing MySQL databases.


What is a Foreign Key?

A foreign key is a field in a table that refers to the primary key of another table.

It is used to establish a relationship between two tables, ensuring that data entered into the foreign key field is also present in the referenced primary key.

Foreign keys are used to enforce referential integrity, preventing orphan records and ensuring data consistency.

Step by Step Guide to Creating a Foreign Key in PHPmyAdmin

  1. Open PHPmyAdmin and select the database in which you want to create the foreign key.
  2. Click on the table that you want to create the foreign key in.
  3. Click on the “Structure” tab.
  4. Scroll down to the bottom of the table structure, and click on the “Relation View” link.
  5. Click on the “Add a foreign key constraint” button.
  6. In the “Foreign Key Constraints” section, specify the following details: a. The name of the foreign key b. The referenced table and column c. The action to be taken in case of an update or delete in the referenced table
  7. Click on the “Go” button to save the foreign key.

Example: Let’s consider two tables, ‘orders’ and ‘customers’, where the ‘orders’ table has a foreign key ‘customer_id’ referencing the primary key ‘id’ in the ‘customers’ table.

CREATE TABLE customers (
  id INT(11) NOT NULL AUTO_INCREMENT,
  name VARCHAR(255) NOT NULL,
  PRIMARY KEY (id)
);

CREATE TABLE orders (
  id INT(11) NOT NULL AUTO_INCREMENT,
  customer_id INT(11) NOT NULL,
  date_ordered DATE NOT NULL,
  PRIMARY KEY (id),
  FOREIGN KEY (customer_id) REFERENCES customers(id)
    ON DELETE CASCADE
);

Conclusion

Foreign keys play a crucial role in maintaining data integrity in databases.

With the step by step guide and code example provided in this tutorial, we hope that you now have a clear understanding of how to create a foreign key in PHPmyAdmin.

If you have any questions or comments, please leave them below.