Skip to content
Advertisement

Foreign key returning empty result set

I’ve created a foreign key to link two tables:

  1. The addresses of my users (foreign key)
  2. User login details (primary key).

However, when I create the foreign key no details that the user enters are saved in the address table. Whereas when the address table doesn’t have a foreign key, it inserts the input into the address table just fine.

I don’t have much experience with MySQL so the error could be something trivial, however I cannot find the solution myself. I am using PHP procedural.

Here is a sample of my database:

Address Table containing foreign key:

1   id Primary          int(11)         No  None        AUTO_INCREMENT      
2   address_fk Index    int(11)         No  None            
3   address_line_one    varchar(25) utf8_general_ci     No  None                
4   address_line_two    varchar(25) utf8_general_ci     No  None    

User details with primary key:

1   id Primary      int(11)         No             None     AUTO_INCREMENT      
2   user_email      varchar(320)    utf8_general_ci     No  None            
3   user_password   char(60)        utf8_general_ci     No  None    

Any guidance would be appreciated.

Advertisement

Answer

A foreign key in a child table has to reference an existing primary key column in the parent table. If your primary key is the ID column in your User Details table, your foreign key will be an ID column in the Addresses table, as it will point to the ID column in your parent table.

Your current setup indicates an address_fk column as the foreign key; however, there is no such column in the User Details table to which it can point.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement