将一个表中的最后一个主键作为外键插入另一个表

I am trying to find a method for inserting the last primary key from Table1 as a foreign key into Table2.

So far, I have tried SELECT max(‘id‘) FROM table1 as foreign_key blablablablablabla

It works if one user registers at that current time; however, if 5 users register at the same time, the foreign key is wrong.

Multiple ways you can do this.

Creating a trigger

You can create a trigger after insert of table1 into table2. For example;

CREATE TRIGGER `add to other table` AFTER INSERT ON `table1`
FOR EACH ROW INSERT INTO table2 SET user_id=NEW.id, name=NEW.username;

Using PHP

You can do this using mysqli::insert_id, for example; (You would bind and sanitize input, but for the sake of illustration, I won't)

 $mysql->query("INSERT INTO `table1` SET `username`='pokrenz'");
 $intForeignKey = $mysql->insert_id;
 $mysql->query("INSERT INTO `table2` SET `id` = ". $intForeignKey);