How to insert data and a table with Foreign Key in PHP/MYSQL

Asked

Viewed 169 times

-1

i have 2 tables Client and Address with relationship 1.1

In the address table has the FK.

What would be the right way to do the Insert in these tables, relating client to address?

I imagine Lastinsertid wouldn’t be viable in a very large system with multiple records being rewired at the same time.

  • 2

    Wellington edit your question and put together your code

  • 1

    Wasn’t it supposed to be the other way around? Customer have foreign address key?

  • The ideal here in the forum is that you put your code so that we can help you better. Question answered with the information you put, if you put more information and it is not compatible with the situation I edit/ remove.

1 answer

0


The ideal is that the customer receives the foreign key from the address and not the other way around. You can use the mysqli_insert_id() or PDO::lastInsertId(), because even if there are several people creating register at the same time, the SGBD will take care of this problem for you.

Each client creates a connection to the database. By Mysql’s own manual: The ID that is generated when using this command on the server is generated based on the connection. This means that the value returned by the function by a specific client is the first AUTO_INCREMENT value generated by that client’s latest command that affects an AUTO_INCREMENT column and this value cannot be affected by other customers, even if they generate other AUTO_INCREMENT values.

  • I put the foreign key on the wrong side really, but the question was really whether to use mysqli_insert_id() or PDO::lastInsertId(). Could it be that if a customer enters records at the same time as another one this can’t be a problem? Why? I would like to know the reason why

  • @Wellington added this information in the comments. I hope you now clarify :D better

Browser other questions tagged

You are not signed in. Login or sign up in order to post.