Good day,
I am willing to retrieve the id value of a freshly inserted row in Mysql.
I know there is mysqli_insert_id function, but:
I don't want to take the risk to query the highest id since there are a lot of queries, it could give me the wrong one...
(My id column is on auto-increment)
If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL.
Get ID of The Last Inserted RecordIf we perform an INSERT or UPDATE on a table with an AUTO_INCREMENT field, we can get the ID of the last inserted/updated record immediately.
you can get the id if you call LAST_INSERT_ID() function immediately after insertion and then you can use it. Show activity on this post. For any last inserted record will be get through mysql_insert_id() If your table contain any AUTO_INCREMENT column it will return that Value.
https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row describes the solution perfectly well:
connection.query('INSERT INTO posts SET ?', {title: 'test'}, function(err, result, fields) {
if (err) throw err;
console.log(result.insertId);
});
var table_data = {title: 'test'};
connection_db.query('INSERT INTO tablename SET ?', table_data , function(err, result, fields) {
if (err) {
// handle error
}else{
// Your row is inserted you can view
console.log(result.insertId);
}
});
You can also view by visiting this link https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With