开发者

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

开发者 https://www.devze.com 2023-03-30 14:12 出处:网络
What I am doing: (wp_posts has ID as primary key and it auto-increase) mysql_query(\"INSERT INTO wp_posts (post_content, post_开发者_Python百科title) VALUES (\'$addEP\', \'$title\')\");

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

mysql_query("INSERT INTO wp_posts (post_content, post_开发者_Python百科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.


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


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

So

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

... is not necessary anymore.


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();.


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.


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


that's what mysql_last_insert_id() is for

0

精彩评论

暂无评论...
验证码 换一张
取 消