如何从WordPress数据库中获取最后插入的行ID? [英] How to get last inserted row ID from WordPress database?

查看:206
本文介绍了如何从WordPress数据库中获取最后插入的行ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的WordPress插件有一个表,该表包含一个名为ID的 AUTO_INCREMENT 主键字段.当在表中插入新行时,我想获取插入的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.

此功能是使用AJAX将数据发布到服务器以插入到DB中.在AJAX响应中返回新的行ID,以更新客户端状态.多个客户端可能同时将数据发布到服务器.因此,我必须确保每个AJAX请求都获得确切的新行ID作为响应.

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.

在PHP中,有一个名为 mysql_insert_id 的方法,但是,仅当参数为 link_identifier时才对竞争条件有效 .我对数据库的操作在$ wpdb上.如何从$ wpdb中提取 link_identifier 以确保mysql_insert_id正常工作?还有其他方法可以从$ wpdb获取最后插入的行ID吗?

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?

谢谢.

推荐答案

在执行插入操作的$wpdb->insert()之后直接执行以下操作:

Straight after the $wpdb->insert() that does the insert, do this:

$lastid = $wpdb->insert_id;

有关如何以WordPress方式进行操作的更多信息,可以在WordPress Codex中找到.上面的详细信息可以在 wpdb类页面

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

这篇关于如何从WordPress数据库中获取最后插入的行ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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