Retrieving the Last Inserted ID with MySQL and Node.js
When dealing with database operations, there are often scenarios where you need to retrieve the ID of the recently inserted row. In MySQL, this can be achieved using the mysqli_insert_id() function. However, for Node.js MySQL users, there are some limitations and security concerns associated with this method.
Overcoming Limitations and Security Risks
The limitations and risks mentioned in the question include:
Solution Using connection.query()
To address these challenges, you can utilize the connection.query() method in Node.js MySQL, as described in the documentation. This approach offers greater control and security:
connection.query('INSERT INTO posts SET ?', {title: 'test'}, function(err, result, fields) { if (err) throw err; console.log(result.insertId); });
In this example, after executing the insert query, the result object contains the insert ID in the insertId property. This method ensures that you retrieve the correct ID and eliminates the risks associated with using mysqli_insert_id().
以上是如何使用 Node.js 檢索 MySQL 中最後插入的 ID?的詳細內容。更多資訊請關注PHP中文網其他相關文章!