How to get a Primary ID before or at the same time it gets created?

China☆狼群 提交于 2019-12-24 17:19:44

问题


What I am doing: (wp_posts has ID as primary key and it auto-increase)

mysql_query("INSERT INTO wp_posts (post_content, post_title) VALUES ('$addEP', '$title')");
$rs = mysql_query("SELECT ID FROM wp_posts WHERE post_title='$title'");
$add_row = mysql_fetch_array($rs);
$add_postid = $add_row['ID'];
mysql_query("INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES ('$add_postid', '$cat_id')");

So basically, what I am doing is; I insert content into wp_posts and then run another query to catch the ID of the post. Then set it into another table.

Is it possible to do this without running the second query to catch the ID? Thanks.


回答1:


$add_postid = mysql_insert_id(); is what you are looking for.

So

$rs = ... // and
$add_row = ...

... is not necessary anymore.




回答2:


You can retrieve the last generated id (per connection) via mysql_insert_id()

edit: The MySQL server also stores that id per connection and you can "retrieve" the id within an sql statement

INSERT INTO
  wp_term_relationships
  (object_id, term_taxonomy_id)
VALUES
  (LAST_INSERT_ID(), '$cat_id')

There are subtle difference between the two "methods" which are explained at http://dev.mysql.com/doc/refman/5.0/en/mysql-insert-id.html




回答3:


mysql_insert_id() will return the value for you, but only AFTER the insert as completed. You can't use it within an insert to catch the new ID, because that ID won't have been assigned yet.

Internally it's doing select last_insert_id();.




回答4:


Without passing the ID of the post manually, you would have to use mysql_insert_id().

Note:

Because mysql_insert_id() acts on the last performed query, be sure to call mysql_insert_id() immediately after the query that generates the value.

On a side note, I would suggest you check out PDO if you have not already.




回答5:


Not that I know of (you have to insert before you can get the right id)...where is the script being ran? Wordpress has a built in class that would perhaps make it easier, it has a variable that stores the insert ID as well:

http://codex.wordpress.org/Class_Reference/wpdb#Class_Variables




回答6:


that's what mysql_last_insert_id() is for



来源:https://stackoverflow.com/questions/7192449/how-to-get-a-primary-id-before-or-at-the-same-time-it-gets-created

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!