简体   繁体   English

mysql和php自动增加id并插入数据

[英]mysql & php auto increment id and insert data

I have two database tables in my sql database. 我的sql数据库中有两个数据库表。 First one is personal table and other one is payment details. 第一个是个人表格,另一个是付款明细。 Auto inctiment id in personal table is used as foreign key of payment details. 个人表中的自动付款编号用作付款明细的外键。 i have to insert data to two this table at a time.normaly I should insertdata to personal table and get auto increment id of this row and insert data to payment data table. 我必须一次将数据插入到此表中的两个表中。通常我应该将数据插入到个人表中,并获取此行的自动增量ID,然后将数据插入到支付数据表中。 but i have some problems. 但是我有一些问题。

  • I can't get auto increment id using my sql SELECT query easily.because there are more colums to check through WHERE. 我无法使用sql SELECT查询轻松获得自动增量ID。因为有更多的列需要通过WHERE进行检查。
  • get last insert id is not perfect way. 获取最后一个插入ID并不是完美的方法。 because other user can insert another person's data while i'm accessing and i receive wrong id. 因为其他用户可以在我访问时插入其他人的数据,并且收到错误的ID。

I have no good knowledge about this. 我对此一无所知。 help me ! 帮我 !

I don't really know your structure, but the best best way here is to use transactions. 我真的不知道您的结构,但是最好的最好方法是使用事务。 Link: http://dev.mysql.com/doc/refman/5.7/en/commit.html . 链接: http : //dev.mysql.com/doc/refman/5.7/en/commit.html

START TRANSACTION;
INSERT /* Your insertion into personalTable */
SELECT @lastId:=LAST_INSERT_ID();
INSERT INTO paymentTable SET (user_id) VALUES (@lastId);
COMMIT;

Also you need to set your TRANSACTION ISOLATION LEVEL to SERIALIZABLE to prevent any transaction violations. 另外,您需要将“事务隔离级别”设置为“ SERIALIZABLE”,以防止发生任何事务违规。

UPD. UPD。 Thanks @Drew to make me dig deeper. 谢谢@Drew让我更深入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM