This article mainly introduces how PHP uses the mysql_insert_id() function to obtain the ID of the newly inserted data or the currently published article. It has a certain reference value. Now I share it with you. Friends in need can refer to it
When inserting data into mysql, many times we want to know the id of the data just inserted, which is very useful to us. The following article will give you a detailed introduction to using the mysql_insert_id() function to obtain the ID of the newly inserted data or the currently published article. Friends in need can refer to it. Friends who are interested can take a look below.
Preface
I recently encountered this problem again at work. How to get the ID of the data just inserted (or the ID of the currently published article) in PHP? ? I feel it is necessary to sort out detailed solutions so that I can also provide help to friends in need, so without further ado, let’s take a look at the detailed solution introduction.
Solution
In fact, it can be achieved by using the mysql_insert_id()
function.
Definition and usage
mysql_insert_id()
The function returns the ID generated by the previous INSERT operation.
Note: If the previous query did not generate an AUTO_INCREMENT ID, mysql_insert_id()
returns 0.
Syntax
mysql_insert_id(connection)
connection Optional. Specifies the MySQL connection. If not specified, the previous connection is used. Parameter description
Description
##mysql_insert_id() Return to the previous step in the given connection The ID number of the AUTO_INCREMENT generated in the INSERT query. If connection is not specified, the last open connection is used.
Tips and Notes
Notes: If you need to save the value for later use, be 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 "刚刚插入的数据ID是:".$id; mysql_close($con);
The difference between static, final, interface and abstract in php
Introduction to curl requesting other interfaces in the php interface
The above is the detailed content of PHP uses the mysql_insert_id() function to obtain the ID of the data just inserted or the currently published article.. For more information, please follow other related articles on the PHP Chinese website!