Owais Kiani Owais Kiani - 1 year ago 83
JSON Question

How to get recent added recode id from mysql in node.js

I am adding new user information in mysql db. how can i get recent added record id so that i can create user login detail. Please mind the environment of this Application.
I'm using
1. Windows
2. NPM, Express
3. MySQL
Here is my code.

var input = JSON.parse(JSON.stringify(req.body));
req.getConnection(function (err, connection) {
var data = {
username : input.username,
pswd : input.pswd,
email : input.email,
phone : input.phone
};
var query = connection.query("INSERT INTO customer set ? ",data, function(err, rows)
{
if (err)
console.log("Error inserting : %s ",err );
//console.log(query.sql);
res.redirect('/dashboard');
});
});

Answer Source

What you want is the insertId attribute:

var query = connection.query("INSERT INTO customer set ? ",data, function(err, result)
{
  ...
  console.log(result.insertId);
  ...
});

Take a look at the docs for more information.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download