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