This question already has an answer here:
so I want to link two tables with a common column "messageID". so first I insert into table 1 to get the Auto incremented id, then take that ID with LAST_INSERT_ID function and give that as the id for table 2:
$db->("INSERT INTO table_1 VALUES('','$message')");
$db->("INSERT INTO table_2 VALUES(LAST_INSERT_ID(),'$message');
but here's my concern, there might be two users running this script simultaneously, so in the few milliseconds between the two queries exicuting the LAST_INSERT_ID
could have changed, so now the two id's are different. Is there any way I can prevent this possibility. I know it is not possible to insert into two tables with one query, which was my first thoughts. Any ideas much appreciated. Thank you
</div>
The LAST_INSERT_ID is local to the connection session, so it will not conflict with a different user making an insert.
You could try using scope_identity, which would be something like this:
$db->("DECLARE @LAST_ID int
INSERT INTO table_1 VALUES('','$message')"
SET @LAST_ID = SCOPE_IDENTITY()
);
$arg = ... $myARR['LAST_ID'] ... //however you want to get the LAST_ID from your query to PHP here
$db->("INSERT INTO table_2 VALUES(@arg,'$message');
or
$db->("DECLARE @LAST_ID int
INSERT INTO table_1 VALUES('','$message')"
SET @LAST_ID = SCOPE_IDENTITY()
INSERT INTO table_2 VALUES(@LAST_ID,'$message')
);
LAST_ID would be the value of the Auto incremented id