Sachi Tekina
Sachi Tekina

Reputation: 1810

How to add values simultaneously to the two related tables in MySQL?

I have this two tables: enter image description here

I also have a dynamic form in which it contains table and the user can add rows and the data from it will be inserted in tblcamealsformdetails but the basis for inserting it is the id from tblcamealsform. How do I insert all the values to the two tables simultaneously?

Here's my form: meal form

Upvotes: 1

Views: 1009

Answers (2)

vrijdenker
vrijdenker

Reputation: 1431

You will enter data first in table tblcamealsform. You insert ID from that query. That ID you will use then to insert the rest of the data, along with the insert ID, in table tblcamealsformdetails.

So you don't do it simultaniously. You add the dependencies first.

To get the insert-id from the last query you executed, you will need mysql_insert_id(). See http://php.net/manual/en/function.mysql-insert-id.php

In answer to the comment what will happen if multiple users use the form at the same time:

Since you open a mysql connection at the top of your script which will result a unique connection pointer and all of the mysql-functions you call automatically reference to that pointer I think mysql_insert_id() will always reference to the latest query performed by the current connection. So another thread by another user would not interfere with this.

Please note that I am not 100% sure about this though.

Anyway: I am using this for about 10 years now some of which include high-traffic websites and I have never experienced any problems using this method, so in my opinion you can safely use it.

There is one exception to this: You must always call mysql_insert_id() immediately after executing the query you want the ID for. If you execute any other query in the meantime (for example, you call a method of another object which performs an insert-query) mysql_insert_id() will return the ID of that query instead. This is mistake I have made in the past and which you have to be aware of.

Upvotes: 3

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27192

I'd like to point you using LAST_INSERT_ID:

when doing multiple-row inserts, LAST_INSERT_ID() will return the value of the first row inserted (not the last).

Upvotes: 0

Related Questions