Mysql INSERT data and return the auto-incremental ID

Source: Internet
Author: User
Tags mysql insert

To return the latest inserted ID in mysql, we only need to call the mysql_insert_id () function in php after the insert operation to obtain the latest auto-increment ID.

How do I return the ID number of the auto-increment ID of the inserted data?

The PHP function mysql_insert_id () returns the value of the field defined by AUTO_INCREMENT after the last INSERT query is executed.

Sample Code

The Code is as follows: Copy code

<? Php
$ Link = mysql_connect ('localhost', 'mysql _ user', 'mysql _ password ');
If (! $ Link ){
Die ('could not connect: '. mysql_error ());
}
Mysql_select_db ('mydb ');

Mysql_query ("insert into mytable (product) values ('kossu ')");
Printf ("Last inserted record has id % dn", mysql_insert_id ());
?>

Mysql query classes are often used in actual programming.

Sample Code:

The Code is as follows: Copy code

$ SQL = "insert into $ tablename set ame = '$ title', author =' $ boke', 'desc' = '$ desc', cat_id =' $ catid ', adddate = '". date ('Y-m-d H: I: s '). "'";
$ Result = $ query-> query ($ SQL );
$ F_id = $ query-> insert_id ();
If ($ result ){
Echo "added successfully. <A href = 'detail. php? Id = $ f_id '> View </a> ";

}

// Insert_id
Public function insert_id (){
Return ($ I1 = mysql_insert_id ($ this-> _ conn)> = 0? $ I1: $ this-> result ("SELECT last_insert_id ();");
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.