如何从 WordPress 数据库获取最后插入的行 ID?
我的 WordPress 插件有一个表,其中包含一个名为 ID 的 AUTO_INCRMENT 主键字段。当新行插入表中时,我想获取插入的 ID 值。
其特点是使用AJAX将数据发布到服务器以插入到数据库中。新的行 ID 在 AJAX 响应中返回以更新客户端状态。多个客户端可能同时向服务器发送数据。因此,我必须确保每个 AJAX 请求都获得准确的新行 ID 作为响应。
在 PHP 中,有一个名为 mysql_insert_id 的方法来实现此功能。但是,仅当参数为 link_identifier 时,它才对竞争条件有效。 > 上次操作的。我对数据库的操作是在 $wpdb 上。如何从 $wpdb 中提取 link_identifier 以确保 mysql_insert_id 正常工作?有没有其他方法可以从 $wpdb 获取最后插入的行 id?
谢谢。
My WordPress plugin has a table with a AUTO_INCREMENT primary key field called ID. When a new row is inserted into the table, I'd like to get the ID value of the insertion.
The feature is to using AJAX to post data to server to insert into DB. The new row ID is returned in the AJAX response to update client status. It is possible that multiple clients are posting data to server at the same time. So, I have to make sure that each AJAX request get the EXACT new row ID in response.
In PHP, there is a method called mysql_insert_id for this feature.But, it is valid for race condition only if the argument is link_identifier of last operation. My operation with database is on $wpdb. How to extract the link_identifier from $wpdb to make sure mysql_insert_id work? Is there any other way to get the last-inserted-row id from $wpdb?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
在执行插入操作的
$wpdb->insert()
之后,执行以下操作:有关如何以 WordPress 方式执行操作的更多信息,请参阅 WordPress 代码。上述详细信息可在 wpdb 类页面上找到
Straight after the
$wpdb->insert()
that does the insert, do this:More information about how to do things the WordPress way can be found in the WordPress codex. The details above were found here on the wpdb class page
这就是我在代码中的做法
更多类变量
This is how I did it, in my code
More Class Variables
我需要在插入后获取最后一个 id 方式,所以
不是一个选项。
是否执行了以下操作:
I needed to get the last id way after inserting it, so
Was not an option.
Did the follow:
像这样获取 WP 中最后插入的行 ID。
Get the last inserted row id in WP like this.
像这样的事情也应该这样做:
Something like this should do it too :
就像这样:
只需选择所有行,然后按 id 对它们进行 DESC 排序,并仅显示第一行
just like this :
simply your selecting all the rows then order them DESC by id , and displaying only the first
将调用 mysql_insert_id() 放入事务中,应该这样做:
Putting the call to
mysql_insert_id()
inside a transaction, should do it: