How to obtain the id of a record when inserting a record into mysql? how to obtain the id of this record when inserting a record into mysql? & nbsp; what is the effect I want? when inserting a record & nbsp; there is a field value to share with id: how to obtain the id value of this record when inserting a record into mysql
How to obtain the id value of this record when inserting a record into mysql
What is the effect I want? when inserting a record, the value of a field must be the same as that of id.
Share: More
------ Solution --------------------
LAST_INSERT_ID () + 1
------ Solution --------------------
Suppose $ db is your database object, and $ SQL is the SQL statement you want to execute.
Run $ db-> query ($ SQL) first );
Run $ last_id = $ db-> insert_id ();
Then $ last_id is the ID you need
------ Solution --------------------
Public function insert ($ data ){
If (! Is_array ($ data)
------ Solution --------------------
Empty ($ data) return 0;
$ Data = $ this-> build_insert ($ data );
$ SQL = sprintf ("INSERT INTO % s", $ this-> table_name, $ data );
$ Result = $ this-> query ($ SQL );
Return $ this-> insert_id ();
}
------ Solution --------------------
When the field id is set to AUTO_INCREMENT auto-increment, you can use the following method to obtain it:
Mysql function: LAST_INSERT_ID ();
Php function: mysql_insert_id ();
Note: If the field is not AUTO_INCREMENT, the above function returns 0;
------ Solution --------------------
After insertion, mysql_insert_id () is the inserted id value.
------ Solution --------------------
The mysql_insert_id () function returns the ID generated by the previous insert operation. If it is not the ID of AUTO_INCREMENT, then mysql_insert_id () returns 0.
------ Solution --------------------
It can be the following idea:
1) insert the primary data first, and leave the field with the id sample value blank;
2) use $ id = mysql_insert_id () to obtain the id of the inserted data;
3) use the update table set field ={$ id} to update the field with the same value as the id.
Or first, find the current largest id, add 1 to the id, then manually insert the id and the field with the same value as the id, set their value to the id after the value is 1