使用mysql_insert_id插入大量数据

发布于 2024-09-19 06:24:54 字数 292 浏览 5 评论 0原文

我想使用PHP和MySQL将数据插入数据表及其关联的多对多表。多对多表中使用数据表的自增主ID。因此,我需要知道要插入多对多表的数据表的 ID。

我目前的想法是,解决此问题的最佳方法是使用循环,它首先插入数据表,然后使用 mysql_insert_id() 插入多对多表。这是解决这个问题的最佳方法吗?

此外,我是否需要担心该函数会获取错误的 id?许多工作人员会同时使用此数据脚本,因此我担心一个工作人员查询的 ID 最终会在另一个工作人员的 mysql_insert_id() 调用中返回。这是一个合理的担忧吗?如果是,我该如何处理?

I want to use PHP and MySQL to insert data into a data table and its associated many-to-many table. The auto-incrementing primary ID of the data table is used in the many-to-many table. So, I need to know the ID's of the data table to insert into the many-to-many table.

My current thinking is that the best way to approach this is with a loop, which would first insert into the data table then use mysql_insert_id() to insert into the many-to-many table. Is that the best way to go about this?

Additionally, do I need to be concerned about getting the wrong id with that function? Many workers would be using this data script at the same time, so my concern is that an ID from one workers query would end up being returned in the call to mysql_insert_id() of another. Is that a valid concern and if so how can I deal with it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

逐鹿 2024-09-26 06:24:54

在具有 auto_increment id 的表上调用 mysql_insert_id() 是正确的方法。

只要在调用mysql_query()插入行后立即调用mysql_insert_id(),就不需要担心获得错误的id。 PHP 和 MySQL 会为您处理这一切。

Calling mysql_insert_id() on a table with an auto_increment id is exactly the right approach.

As long as you call mysql_insert_id() straight after you call mysql_query() to insert the row, you don't need to worry about getting the wrong id. PHP and MySQL look after all that for you.

你穿错了嫁妆 2024-09-26 06:24:54

如果你可以锁定桌子。

LOCK TABLE myTable FOR WRITE;
SELECT MAX(id) FROM myTable;
INSERT....
INSERT....
INSERT....
SELECT MAX(id) FROM myTable;
UNLOCK TABLES;

这将阻止其他人对 myTable 执行任何操作,但您将获得 id 的最小/最大范围。

-丹尼尔

If you can just lock the table.

LOCK TABLE myTable FOR WRITE;
SELECT MAX(id) FROM myTable;
INSERT....
INSERT....
INSERT....
SELECT MAX(id) FROM myTable;
UNLOCK TABLES;

This will prevent anyone else from doing anything with myTable, but you will then have the min/max range for your ids.

-daniel

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文