Skip to content
Advertisement

Inserting data into a table using foreign keys in MySQL

I am trying to insert data into a contacts table using foreign keys in mysql, the structure of tables are as follows

The fk_id in the contacts table is the FOREIGN KEY and it relates to the pers_id PRIMARY KEY in the users table, I am trying to insert a new contact with relates to a user in the users table

All is done in PHP with MySQl. I used this sql statement shown below in the code but it does not work

Hope anyone could help

Advertisement

Answer

You can use insert ... select:

For this to properly work, username should be a unique key in the users table.

You could also express this as follows:

Note that I rewrote the statement to use proper parameters. Never concatenate data coming from outside your program in a query string: this opens up your code to SQL injection. Recommended reading: How can I prevent SQL injection in PHP?.

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