How to get the ID value of this record when inserting a record into MySQL

Source: Internet
Author: User
How to get the ID value of this record when inserting records into MySQL
How to get the ID value of this record when inserting records into MySQL
What's the effect I want? When inserting a record, the value of a field is the same as the ID.

Share to: more


------Solution--------------------
LAST_INSERT_ID (+1)
------Solution--------------------
Suppose $db is your database object, $sql is the SQL statement you want to execute.
Execute $db->query ($sql) first;
Re-execute $last_id = $db->insert_id ();
Then $LAST_ID is the ID you need.
------Solution--------------------

Public Function Insert ($data) {

------Solution--------------------
Empty ($data)) return 0;
$data = $this->build_insert ($data);
$sql = sprintf ("INSERT into%s%s", $this->table_name, $data);
$result = $this->query ($sql);
return $this->insert_id ();
}

------Solution--------------------
When the field ID is set to auto_increment, it can be obtained using the following method:
MySQL function: last_insert_id ();
PHP function: mysql_insert_id ();

Note: If the field is not auto_increment, the above function will return 0;
------Solution--------------------
After inserting, mysql_insert_id () This is the ID value of the insertion
------Solution--------------------
The mysql_insert_id () function returns the ID generated by the previous insert operation. If it is not a self-increment (auto_increment) ID, then mysql_insert_id () returns 0.
------Solution--------------------
Can be a way of thinking:
1) First insert the master data, and the ID-like value of the field is left blank;
2) then use $id = mysql_insert_id () to get the ID of the data just inserted;
3) Use the Update table set field ={$id} to change that field to the same value as the ID

Or first find out the current maximum ID, the ID plus 1, and then manually insert the ID and the same value as the ID of the field, set their value is equal to 1 after the ID
  • 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.