Retrieve last inserted id with Mysql

Mysqlnode.js

Mysql Problem Overview


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)

Mysql Solutions


Solution 1 - Mysql

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);
});

Solution 2 - Mysql

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

Solution 3 - Mysql

I think you misunderstood the use of mysqli_insert_id() method. This method must be executed immediately after the insert statement to obtain the last inserted id. if you do it my MySQL directly

INSERT INTO(a,b)values(1,'test');
SELECT LAST_INSERT_ID();  -- this will display the last inserted id

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlopataView Question on Stackoverflow
Solution 1 - MysqllukschView Answer on Stackoverflow
Solution 2 - MysqlVIKAS KOHLIView Answer on Stackoverflow
Solution 3 - MysqlJaylenView Answer on Stackoverflow