How do i set foreign key in phpmyadmin?

I'm setting up a database using phpMyAdmin. I have two tables (foo and bar), indexed on their primary keys. I am trying to create a relational table (foo_bar) between them, using their primary keys as foreign keys.

I created these tables as MyISAM, but have since changed all three to InnoDB, because I read that MyISAM doesn't support foreign keys. All id fields are INT(11).

When I choose the foo_bar table, click the "relation view" link, and try to set the FK columns to be database.foo.id and database.bar.id, it says "No index defined!" beside each column.

What am I missing?

Clarification/Update

For the sake of simplicity, I want to keep using phpMyAdmin. I am currently using XAMPP, which is easy enough to let me focus on the PHP/CSS/Javascript, and it comes with phpMyAdmin.

Also, although I haven't been able to set up explicit foreign keys yet, I do have a relational table and can perform joins like this:

SELECT * 
FROM foo 
INNER JOIN foo_bar 
ON foo.id = foo_bar.foo_id 
INNER JOIN bar
ON foo_bar.bar_id = bar.id;

It just makes me uncomfortable not to have the FKs explicitly defined in the database.


1) Solution

If you want to use phpMyAdmin to set up relations, you have to do 2 things. First of all, you have to define an index on the foreign key column in the referring table (so foo_bar.foo_id, in your case). Then, go to relation view (in the referring table) and select the referred column (so in your case foo.id) and the on update and on delete actions.

I think foreign keys are useful if you have multiple tables linked to one another, in particular, your delete scripts will become very short if you set the referencing options correctly.

EDIT: Make sure both of the tables have the InnoDB engine selected.

2) Solution

phpMyAdmin lets you define foreign keys using their "relations" view. But since, MySQL only supports foreign constraints on "INNO DB" tables, the first step is to make sure the tables you are using are of that type.

To setup a foreign key so that the PID column in a table named CHILD references the ID column in a table named PARENT, you can do the following:

  1. For both tables, go to the operations tab and change their type to "INNO DB"
  2. Make sure ID is the primary key (or at least an indexed column) of the PARENT table.
  3. In the CHILD table, define an index for the PID column.
  4. While viewing the structure tab of the CHILD table, click the "relation view" link just above the "add fields" section.
  5. You will be given a table where each row corresponds to an indexed column in your CLIENT table. The first dropdown in each row lets you choose which TABLE->COLUMN the indexed column references. In the row for PID, choose PARENT->ID from the dropdown and click GO.

By doing an export on the CHILD table, you should see a foreign key constraint has been created for the PID column.

3) Solution

This is a summary of a Wikipedia article. It specifies the different types of relationships you can stipulate in PHPmyadmin. I am putting it here because it is relevant to @Nathan's comment on setting the foreign keys options for "on update/delete" but is too large for a comment - hope it helps.

CASCADE

Whenever rows in the master (referenced) table are deleted (resp. updated), the respective rows of the child (referencing) table with a matching foreign key column will get deleted (resp. updated) as well. This is called a cascade delete (resp. update[2]).

RESTRICT

A value cannot be updated or deleted when a row exists in a foreign key table that references the value in the referenced table. Similarly, a row cannot be deleted as long as there is a reference to it from a foreign key table.

NO ACTION

NO ACTION and RESTRICT are very much alike. The main difference between NO ACTION and RESTRICT is that with NO ACTION the referential integrity check is done after trying to alter the table. RESTRICT does the check before trying to execute the UPDATE or DELETE statement. Both referential actions act the same if the referential integrity check fails: the UPDATE or DELETE statement will result in an error.

SET NULL

The foreign key values in the referencing row are set to NULL when the referenced row is updated or deleted. This is only possible if the respective columns in the referencing table are nullable. Due to the semantics of NULL, a referencing row with NULLs in the foreign key columns does not require a referenced row.

SET DEFAULT

Similar to SET NULL, the foreign key values in the referencing row are set to the column default when the referenced row is updated or deleted.

4) Solution

In phpmyadmin, you can assign Foreign key simply by its GUI. Click on the table and go to Structure tab. find the Relation View on just bellow of table (shown in below image).

How do i set foreign key in phpmyadmin?

You can assign the forging key from the list box near by the primary key.(See image below). and save

How do i set foreign key in phpmyadmin?

corresponding SQL query automatically generated and executed.

5) Solution

For those new to database .... and need to ALTER an existing table. A lot things seem to be pretty straightforward, but there is always something ... between A and B.

Before anything else, take a look at this.

  1. Make sure you have P_ID (parent ID on both parent and child table).
  2. Of course it will be already filled in the parent. Not necessarily in the child in a true and final way. So for instance P_ID #3 (maybe many times in the child table will be pointing to original P_ID at parent table).
  3. Go to SQL tab (I am using phpMyAdmin, should be similar in other ones) and do this command:

    ALTER TABLE child_table_name    
    ADD FOREIGN KEY (P_ID)   
    REFERENCES parent_table_name (P_ID)
    
  4. Click on child table, than structure, finally on relational view. Finish your DB planning there. There was a nice answer before this one about cascade, restrict, etc. Of course it could be done by commands...

6) Solution

Foreign key means a non prime attribute of a table referes the prime attribute of another *in phpMyAdmin* first set the column you want to set foreign key as an index

then click on RELATION VIEW

there u can find the options to set foreign key

7) Solution

InnoDB allows you to add a new foreign key constraint to a table by using ALTER TABLE:

ALTER TABLE tbl_name
    ADD [CONSTRAINT [symbol]] FOREIGN KEY
    [index_name] (index_col_name, ...)
    REFERENCES tbl_name (index_col_name,...)
    [ON DELETE reference_option]
    [ON UPDATE reference_option]

On the other hand, if MyISAM has advantages over InnoDB in your context, why would you want to create foreign key constraints at all. You can handle this on the model level of your application. Just make sure the columns which you want to use as foreign keys are indexed!

8) Solution

Don't forget that the two columns should have the same data type.

for example if one column is of type INT and the other is of type tinyint you'll get the following error:

Error creating foreign key on [PID column] (check data types)

9) Solution

This is old thread but answer because if useful to anyone.

Step 1. Your Db Storage Engine set to InnoDB

Step 2. Create Primary Table

here customer is primary table and customer_id is primary key

How do i set foreign key in phpmyadmin?

Step 3. create foreign key table and give index

here we have customer_addresses as related table and store customer addresses, so here customer_id relation with customer table

we can select index directly when create table as below

How do i set foreign key in phpmyadmin?

If you forgot to give index when create a table, then you can give index from the structure tab of table as below.

How do i set foreign key in phpmyadmin?

Step 4. Once index give to the field, Go to structure tab and click on Relation View as shown in below pic

How do i set foreign key in phpmyadmin?

Step 5. Now select the ON DELETE and ON UPDATE what you want to do, Select column from current table, select DB (SAME DB), select relation table and primary key from that table as shown in below pic and Save it

How do i set foreign key in phpmyadmin?

Now check if relation are give successfully, go to foreign table data list and click on foreign key value, you will redirect to primary table record, then relation made successfully.

10) Solution

Make sure you have selected your mysql storage engine as Innodb and not MYISAM as Innodb storage engine supports foreign keys in Mysql.

Steps to create foreign keys in phpmyadmin:

  1. Tap on structure for the table which will have the foreign key.
  2. Create INDEX for the column you want to use as foreign key.
  3. Tap on Relation view, placed below the table structure

How do i set foreign key in phpmyadmin?

  1. In the Relation view page, you can see select options in front of the field (which was made an INDEX).

How do i set foreign key in phpmyadmin?

UPDATE CASCADE specifies that the column will be updated when the referenced column is updated,

DELETE CASCADE specified rows will be deleted when the referenced rows are deleted.

Alternatively, you can also trigger sql query for the same

ALTER TABLE table_name
ADD CONSTRAINT fk_foreign_key_name
FOREIGN KEY (foreign_key_name)
REFERENCES target_table(target_key_name);

11) Solution

Step 1: You have to add the line: default-storage-engine = InnoDB under the [mysqld] section of your mysql config file (my.cnf or my.ini depending on your OS) and restart the mysqld service.

How do i set foreign key in phpmyadmin?

Step 2: Now when you create the table you will see the type of table is: InnoDB

How do i set foreign key in phpmyadmin?

Step 3: Create both Parent and Child table. Now open the Child table and select the column U like to have the Foreign Key: Select the Index Key from Action Label as shown below.

How do i set foreign key in phpmyadmin?

Step 4: Now open the Relation View in the same child table from bottom near the Print View as shown below.

How do i set foreign key in phpmyadmin?
Step 5: Select the column U like to have the Foreign key as Select the Parent column from the drop down. dbName.TableName.ColumnName

Select appropriate Values for ON DELETE and ON UPDATE

How do i set foreign key in phpmyadmin?

12) Solution

First set Storage Engine as InnoDB

How do i set foreign key in phpmyadmin?

then the relation view option enable in structure menu

How do i set foreign key in phpmyadmin?

13) Solution
14) Solution

Newer versions of phpMyAdmin don't have the "Relation View" option anymore, in which case you'll have to execute a statement to achieve the same thing. For example

ALTER TABLE employees
    ADD CONSTRAINT fk_companyid FOREIGN KEY (companyid)
    REFERENCES companies (id)
    ON DELETE CASCADE;

In this example, if a row from companies is deleted, all employees with that companyid are also deleted.

Related Topics mysql phpmyadminComments12 years, 11 months agoForeign key constraints save me a lot of effort and potential errors. For example, let's say I'm going to delete a user from my system. I could write code that specifies every place in the database where data about that user exists, and tell it to delete it. But I have to keep that delete function up-to-date at all times. On the other hand, if all user-related data has has a FK to the user's ID and is set to cascade on delete, all my code has to say is "delete this user" and the database will take care of deleting everything that has a FK reference to that user. Much cleaner to maintain.12 years, 11 months ago@Nathan: That's what I'm saying in the post. You can handle that on the model level too. You can implement on delete cascade from the model.10 years, 3 months agoYou almost always add referential integrity to your database tables. The database should protect itself from bad application programming. Do not rely on your application alone to maintain data integrity. Of course there are always exceptions to every rule, but I have not found one for this.8 years, 7 months agoTip: Relations view is little link under your table, it was hard for me to find it in the first place8 years, 6 months agoWow, very important thing to know. This page was not the first thing I found when looking for help with adding a foreign key, I wish this were mentioned more often.7 years, 11 months agoUnless that link doesn't show there, in which case: Make sure your table is of type InnoDB (under the Operations tab in phpMyAdmin) for this to not happen.7 years ago@muttley91My table is InnoDB. I double-checked. The link still doesn't show up.5 years, 8 months agoBetter yet, go directly to the MySQL source documentation: dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html4 years, 5 months ago@afilina In the new version of phpMyAdmin, it is visible at the top inside "Structure" tab, just below the tab row that shows "Browse", "Structure", etc.2 years, 8 months agoyour first step is correct but what about next please write all the process step by step.Mentions Community Nathan Long tRuEsAtM user254875486 ThiefMaster awais Neuron Brett Menuka Ishan Nishad Up user2060451 Shafeeq M kunjumoideen markus pouya Devsi Odedra Ankit Jindal marc_s Vinod Sahil Ralkar Jaime Montoya Vincent

Where is the foreign key in phpMyAdmin?

To see FKs of a table first select table from the object explorer, then go to Structure tab and then select Relation view. Please note that in different versions it might be in different locations. On the Relation view screen you will see all foreign keys defined for this table (as a foreign table).

How do I add a key to phpMyAdmin?

Adding a Primary Key to a New Table In phpMyAdmin. When creating a new table in phpMyAdmin, select PRIMARY from the Index dropdown on the column that will be the primary key. Check the box in the A_I column if this will be an auto incrementing key.

How do I manually add a foreign key?

To add a foreign key, click the last row in the Foreign Key Name list. Enter a name for the foreign key and select the column or columns that you wish to index by checking the column name in the Column list. You can remove a column from the index by removing the check mark from the appropriate column.

How do I enable foreign key?

If we then wanted to enable the foreign key, we could execute the following command: ALTER TABLE inventory CHECK CONSTRAINT fk_inv_product_id; This foreign key example would use the ALTER TABLE statement to enable the constraint called fk_inv_product_id on the inventory table.