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

查看:38
本文介绍了如何从 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将数据发布到服务器以插入到数据库中.新行 ID 在 AJAX 响应中返回以更新客户端状态.多个客户端可能同时将数据发布到服务器.因此,我必须确保每个 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 代码中找到.上述详细信息可在 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天全站免登陆