如何从 WordPress 数据库中获取最后插入的行 ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1576018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get last inserted row ID from WordPress database?
提问by Morgan Cheng
My WordPress plugin has a table with a AUTO_INCREMENTprimary key field called ID. When a new row is inserted into the table, I'd like to get the ID value of the insertion.
我的 WordPress 插件有一个表,其中包含一个名为 ID的AUTO_INCREMENT主键字段。当新行插入表中时,我想获取插入的 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.
功能是使用 AJAX 将数据发布到服务器以插入到数据库中。新行 ID 在 AJAX 响应中返回以更新客户端状态。多个客户端可能同时将数据发布到服务器。因此,我必须确保每个 AJAX 请求都获得准确的新行 ID 作为响应。
In PHP, there is a method called mysql_insert_idfor this feature.But, it is valid for race condition only if the argument is link_identifierof last operation. My operation with database is on $wpdb. How to extract the link_identifierfrom $wpdb to make sure mysql_insert_id work? Is there any other way to get the last-inserted-row id from $wpdb?
PHP 中有一个方法叫做mysql_insert_id用于这个特性。但是,只有当参数是最后一次操作的link_identifier 时,它才对竞争条件有效。我对数据库的操作是在 $wpdb 上。如何从 $wpdb 中提取link_identifier以确保 mysql_insert_id 工作?有没有其他方法可以从 $wpdb 获取最后插入的行 ID?
Thanks.
谢谢。
回答by jsnfwlr
Straight after the $wpdb->insert()
that does the insert, do this:
直后$wpdb->insert()
,做的插入,这样做:
$lastid = $wpdb->insert_id;
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 方式做事的更多信息,请参阅 WordPress 法典。上面的详细信息可以在wpdb 类页面上找到
回答by Francisco Corrales Morales
This is how I did it, in my code
这就是我在我的代码中做到的
...
global $wpdb;
$query = "INSERT INTO... VALUES(...)" ;
$wpdb->query(
$wpdb->prepare($query)
);
return $wpdb->insert_id;
...
回答by Marco Floriano
I needed to get the last id way after inserting it, so
我需要在插入后获取最后一个 id 的方式,所以
$lastid = $wpdb->insert_id;
Was not an option.
不是一个选择。
Did the follow:
有没有做到以下几点:
global $wpdb;
$id = $wpdb->get_var( 'SELECT id FROM ' . $wpdb->prefix . 'table' . ' ORDER BY id DESC LIMIT 1');
回答by Martin
Something like this should do it too :
像这样的事情也应该这样做:
$last = $wpdb->get_row("SHOW TABLE STATUS LIKE 'table_name'");
$lastid = $last->Auto_increment;
回答by Ollie Saunders
Putting the call to mysql_insert_id()
inside a transaction, should do it:
将调用mysql_insert_id()
放入事务中,应该这样做:
mysql_query('BEGIN');
// Whatever code that does the insert here.
$id = mysql_insert_id();
mysql_query('COMMIT');
// Stuff with $id.