Re: mysql: get id of just-added record

  • From: Jeff Berwick <mailinglists@xxxxxxxxxxxx>
  • To: programmingblind@xxxxxxxxxxxxx
  • Date: Wed, 11 May 2011 20:48:00 -0400

You can use the mysql_insert_id() function.  If you are using the newer mysqli 
libraries, I believe the function is mysqli_insert_id().

That will return the id of the last inserted record.

Hth,
Jeff

On 2011-05-11, at 7:44 PM, Alex Hall wrote:

> Hi all,
> I have a mysql question. My php script is adding an article to a
> database. However, it must also add one or more rows to an
> article_products table, which consists of just two fields, an article
> id and a product id, which form a composite primary key. The problem
> is that the article_products table can't be updated until the script
> knows the id of the article being added, so I need two separate
> queries to create everything: create the article, then create all rows
> necessary in the article_products table. My question, therefore, is:
> what is the best way to get the id of the article just created? The id
> is an auto_increment integer. I have so far thought about pulling the
> first record when records are sorted in descending order by id, but it
> seems like there might be a better way. If not, what would the syntax
> be? I plan on using something like:
> select article_id from articles sort by article_id desc limit 1;
> Is there a better way? Thanks in advance.
> 
> -- 
> Have a great day,
> Alex (msg sent from GMail website)
> mehgcap@xxxxxxxxx; http://www.facebook.com/mehgcap
> __________
> View the list's information and change your settings at 
> //www.freelists.org/list/programmingblind
> 

__________
View the list's information and change your settings at
//www.freelists.org/list/programmingblind

Other related posts: