Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
610 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...