Retrieving Last Inserted ID in MySQL Using Node.js
In MySQL, the mysqli_insert_id() function can be used to retrieve the ID of the last inserted row. However, in Node.js, using this function may pose certain limitations and potential risks.
If you encounter the following issues when using mysqli_insert_id():
Consider the following alternative solution provided by the MySQL documentation:
connection.query('INSERT INTO posts SET ?', {title: 'test'}, function(err, result, fields) { if (err) throw err; console.log(result.insertId); });
This code uses the result.insertId property to retrieve the ID of the last inserted row. By specifying the table name in the SQL query, you ensure that the correct ID is retrieved. Additionally, executing the query immediately after the INSERT statement eliminates the risk of retrieving an incorrect ID due to concurrent queries.
The above is the detailed content of How to Retrieve Last Inserted ID in MySQL Using Node.js Safely?. For more information, please follow other related articles on the PHP Chinese website!