[PHP] MySQL obtains the primary key (auto-increment ID) and mysql primary key of the inserted data.

Source: Internet
Author: User
Tags mysql functions

[PHP] MySQL obtains the primary key (auto-increment ID) and mysql primary key of the inserted data.


To prevent primary key conflicts, auto-increment (auto_increment type) fields are often used in DB Design. Therefore, the primary key of the modified record is often unknown before data is inserted. To facilitate subsequent or cascade queries, we need to obtain the primary key automatically generated by the database after inserting a row of record. Here we have sorted out the following methods:


  • DB Query


SELECT max(id) FROM user;

The disadvantage of this method is that it is not suitable for high concurrency. The returned values may be inaccurate at the same time.



Note: If you use an INSERT statement to INSERT multiple rows, LAST_INSERT_ID () Only returns the value generated when inserting the first row of data. This makes it easy to copy the same INSERT Statement on other servers.


select @@IDENTITY;

@ Identity refers to the value of the auto-incrementing column corresponding to the last time data is inserted into a table with the identity attribute (that is, the auto-incrementing column). It is a global variable defined by the system. Generally, global variables defined by the system start with @ and User-Defined variables start. For example, if the auto-increment column of Table A is id, after A row of data is inserted into Table A, if the value of the auto-increment column is automatically increased to 101 after the data is inserted, the value obtained through select @ identity is 101. The premise of using @ identity is that the connection is not closed when select @ identity is executed after the insert operation. Otherwise, the value is NULL.

SCOPE_IDENTITY, IDENT_CURRENT, and @ IDENTITY are functionally similar, because they all return values inserted into the IDENTITY column.

IDENT_CURRENT is not restricted by the scope and session, but by the specified table. IDENT_CURRENT returns the value generated for a specific table in any session and scope. For more information, see IDENT_CURRENT.

SCOPE_IDENTITY and @ IDENTITY return the last id value generated in any table in the current session. However, SCOPE_IDENTITY only returns the value inserted into the current scope; @ IDENTITY is not limited to a specific scope.


  • Server Language Query

PHP: mysql_insert_id (Connection);OrMysqli_insert_id (Connection);


Description required. Specifies the MySQL connection to be used.

<?php$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')";$result = mysql_query($sql,$con);echo "ID of last inserted record is: " . mysql_insert_id();mysql_close($con);?>
<?php$con=mysqli_connect("localhost","my_user","my_password","my_db");// Check connectionif (mysqli_connect_errno($con)){echo "Failed to connect to MySQL: " . mysqli_connect_error();}mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Glenn','Quagmire',33)");// Print auto-generated idecho "New record has id: " . mysqli_insert_id($con); mysqli_close($con);?>



PHP-MySQL is the most primitive Extension for PHP to operate MySQL databases. I of PHP-MySQLi stands for Improvement and provides more advanced functions. Extension also increases security.

A. The concepts of mysql and mysqli are related:

  • Mysql and mysqli are both function sets in php and are not associated with mysql databases.
  • Before php5, php mysql functions are generally used to drive mysql databases. For example, mysql_query () functions are process-oriented. 3. After php5, the function of mysqli is added. In a sense, it is an enhanced version of mysql system functions, which is more stable, efficient, and secure. mysqli_query () corresponds to mysql_query (), it is an object-oriented, and uses an object-driven mysql database.

B. Differences between mysql and mysqli:

  • Mysql does not support the connection function. Each connection to mysql opens a connection process.
  • Mysqli is a permanent connection function. mysqli runs mysqli multiple times and uses the same connection process to reduce the overhead of the server. Mysqli encapsulates some advanced operations, such as transactions, and many available methods in the database operation process.

C. Usage of mysql and mysqli:

  • Mysql (Procedure ):
$ Conn = mysql_connect ('localhost', 'user', 'Password'); // connect to mysql database mysql_select_db ('data _ base '); // select database $ result = mysql_query ('select * from data_base '); // the second optional parameter, specifying the connection to be opened $ row = mysql_fetch_row ($ result )) // obtain only one row of Data echo $ row [0]; // output the value of the first field

PS: mysqli operates in a procedural manner. Some functions must specify resources, such as mysqli_query (resource ID, SQL statement), andThe parameters of the resource ID are placed beforeThe resource ID of mysql_query (SQL statement, 'Resource identified') is optional. The default value is the previous opened connection or resource.

  • Mysqli (Object method ):
$ Conn = new mysqli ('localhost', 'user', 'Password', 'Data _ base'); // use the new operator, the last parameter is to directly specify the database // if this parameter is not specified during the construction, the next sentence requires $ conn-> select_db ('data _ base ') implement $ result = $ conn-> query ('select * from data_base '); $ row = $ result-> fetch_row (); // retrieve a row of Data echo row [0]; // output the value of the first field

When new mysqli ('localhost', usenamer ', 'Password', 'databasename') is used, an error is returned, and the prompt is as follows:

Fatal error: Class 'mysqli' not found in...

In general, mysqli is not enabled, because the mysqli class is not enabled by default. In Windows, you need to change php. ini and remove php_mysqli.dll; in linux, You need to compile mysqli.

D. mysql_connect () and mysqli_connect ()

  • Using mysqli, you can pass the database name as a parameter to the mysqli_connect () function, or to the mysqli constructor;
  • If you call the mysqli_query () or mysqli object query () method, the connection ID is required.

JDBC 2.0: insertRow ()

Statement stmt = null; ResultSet rs = null; try {stmt = conn. createStatement (java. SQL. resultSet. TYPE_FORWARD_ONLY, // create Statement java. SQL. resultSet. CONCUR_UPDATABLE); stmt.exe cuteUpdate ("drop table if exists autoIncTutorial"); stmt.exe cuteUpdate (// CREATE demo TABLE "create table autoIncTutorial (" + "priKey int not null AUTO_INCREMENT, "+" dataField VARCHAR (64), primary key (priKey) "); rs = stmt.exe cuteQ Uery ("SELECT priKey, dataField" // retrieve data + "FROM autoIncTutorial"); rs. moveToInsertRow (); // move the cursor to the row to be inserted (uncreated pseudo record) rs. updateString ("dataField", "auto increment here? "); // Modify the rs content. insertRow (); // insert record rs. last (); // move the cursor to the last line int autoIncKeyFromRS = rs. getInt ("priKey"); // obtain the primary key preKey rs of the newly inserted record. close (); rs = null; System. out. println ("Key returned for inserted row:" + autoIncKeyFromRS);} finally {// rs, stmt close () Cleanup}

JDBC 3.0: getGeneratedKeys ()

Statement stmt = null; ResultSet rs = null; try {stmt = conn. createStatement (java. SQL. resultSet. TYPE_FORWARD_ONLY, java. SQL. resultSet. CONCUR_UPDATABLE );//... // omit several rows (create demo table as shown in the preceding example )//... stmt.exe cuteUpdate ("insert into autoIncTutorial (dataField)" + "values ('Can I Get the Auto Increment Field? ') ", Statement. RETURN_GENERATED_KEYS); // specifies to the driver that the generatedKeys must be automatically obtained! Int autoIncKeyFromApi =-1; rs = stmt. getGeneratedKeys (); // get the auto-incrementing primary key! If (rs. next () {autoIncKeyFromApi = rs. getInt (1);} else {// throw an exception from here} rs. close (); rs = null; System. out. println ("Key returned from getGeneratedKeys ():" + autoIncKeyFromApi);} finally {...}

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.