Retrieving Last Inserted ID with MySQL and Node.js
In MySQL, obtaining the ID of a newly inserted row is a common operation. However, relying solely on the mysqli_insert_id function can pose limitations. To address these concerns for developers using Node.js MySQL:
Limitations of mysqli_insert_id:
Solution:
The recommended solution is to use the MySQL driver's insertId property, which provides a reliable method for retrieving the last inserted ID. Here's an example:
const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'username', password: 'password', database: 'database_name', }); connection.query('INSERT INTO posts SET ?', { title: 'test' }, (err, result, fields) => { if (err) throw err; console.log(result.insertId); });
Benefits of this Approach:
The above is the detailed content of How to Reliably Retrieve the Last Inserted ID in MySQL with Node.js?. For more information, please follow other related articles on the PHP Chinese website!