Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve last inserted id with Mysql

Tags:

node.js

mysql

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:

  1. I can't specify the table
  2. Maybe there would be a risk of retrieving the wrong id, if a query is made in the meanwhile.
  3. I am using node.js MySQL

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)

like image 372
lopata Avatar asked Jul 12 '15 18:07

lopata


People also ask

How do I get the last inserted id in MySQL?

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.

How do I get the last insert ID from a specific table?

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.

How do I get last inserted data?

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.


2 Answers

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);
});
like image 96
luksch Avatar answered Oct 12 '22 12:10

luksch


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

like image 26
VIKAS KOHLI Avatar answered Oct 12 '22 12:10

VIKAS KOHLI