你能相信mysql_insert_id吗? [英] Can you trust mysql_insert_id?

查看:98
本文介绍了你能相信mysql_insert_id吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个注册页面,然后将数据插入MySQL的两个表中。第一个是技术信息,如用户名/密码/电子邮件,另一个是个人信息,如姓名/地址等。

I have a registration page which then inserts data into two tables in MySQL. The first one is technical information like username/password/email, and the other one is for personal information like name/address and such.

我的技术信息表有一个主要信息键自动增量ID,然后,一旦我在此表中创建行,我立即在具有相同ID的常规信息表中创建另一行。

My technical information table has a primary key auto incremental ID, and then, once I create the row in this table, I immediately create another row in the general information table with the same id.

要获取该ID,我在第一次插入查询后立即使用 mysql_insert_id()函数。

To obtain that ID, I use the mysql_insert_id() function right after the first insert query.

我的问题相当笼统:你真的相信这个函数它必然会返回相应的索引吗?如果我的网站有很多用户注册怎么办?每一秒,它仍然可靠,并始终返回ID?或者它只返回生成的表的最后一个主键?

My question is rather general: can you really trust this function that it will necessarily return the appropriate index? What if I had a website with many users registering every second, would it still be reliable, and always return the ID? Or does it just return the last primary key of a table generated?

推荐答案

是的,你可以。

该函数是每个会话,但它也只对最后一个查询有效。

The function is per-session, but it is also only valid for the very last query.

也就是说,你永远不会让一个用户污染另一个的last_insert_id,但是你无法从两次插入前恢复insert_id。当您需要连续执行多个插入并且之后不需要ID时,请将它们设置为变量:

That is, you'll never have one user "polluting" the last_insert_id of another, but you cannot recover an insert_id from two inserts ago. When you need to do several inserts in a row and don't need the ids until later, set them as variables:

INSERT INTO ...
SET @foo_id = LAST_INSERT_ID();
INSERT INTO ...
SET @bar_id = LAST_INSERT_ID();
INSERT INTO some_join_table VALUES (@foo_id, @bar_id);

这篇关于你能相信mysql_insert_id吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆