This article mainly introduces about PHP with the mysql_insert_id () function to get just inserted data or the current published article ID, has a certain reference value, now share to everyone, the need for friends can refer to
When inserting data into MySQL, many times we want to know the ID of the data we just inserted, which is useful for us. The following article on the detailed introduction of the use of the mysql_insert_id () function to obtain the newly inserted data or the current published article ID, the need for friends can reference, interested friends below to see it together.
Objective
How do you get the ID of the newly inserted data (or the ID of the currently published article) in PHP when I recently encountered this problem at work? Feel the need to tidy up the detailed solution, to facilitate their own needs to provide friends to help, then not much to say, to see a detailed solution to the introduction.
Workaround
In fact mysql_insert_id()
, it can be achieved with a function.
Definition and usage
mysql_insert_id()
The function returns the ID generated by the previous INSERT operation.
Note: If the previous query does not produce an ID of auto_increment, it mysql_insert_id()
returns 0.
Grammar
MYSQL_INSERT_ID (Connection)
Connection is optional. Specify MySQL connection. If not specified, the previous connection is used. parameter Description
Description
mysql_insert_id()
Returns the ID number of the auto_increment generated in the previous INSERT query in the given connection. If connection is not specified, the previous open connection is used.
Hints and Notes
Note: If you need to save the value for later use, make sure to call it immediately after the query that produced the value. mysql_insert_id()
Example
$con = mysql_connect ("localhost", "Hello", "321"), if (! $con) {die (' Could not connect: '. Mysql_error ());} $db _selected = mysql_select_db ("test_db", $con); $sql = "INSERT into person VALUES (' Carter ', ' Thomas ', ' Beijing ')"; mysql_query ($sql, $con); $id = mysql_insert_id () echo " The data ID you just inserted is: ". $id; Mysql_close ($con);
The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!