node.js & mysql - How to get the last inserted ID?

10k views Asked by At
db.query("INSERT INTO `chat_entries`(`author`, `authorRank`, `receiver`, `timestamp`, `message`) VALUES (" + db.escape(GetUsername(connection)) + ", " + GetUserData(GetUsername(connection), "rank") + ", '-', " + Math.round(new Date().getTime() / 1000) + ", '" + db.escape(messageData.message) + "')", function(result, rows){
    console.log(result.insertId);
});

The console told me:

Cannot read property 'insertId' of null

After I had searched for a solution I found this page: https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row

According to this documentation, it must work. Where's my mistake? Thanks in advance.

3

There are 3 answers

2
Adam On

Your callback params are wrong. Try this:

db.query("INSERT INTO `chat_entries`(`author`, `authorRank`, `receiver`, `timestamp`, `message`) VALUES (" + db.escape(GetUsername(connection)) + ", " + GetUserData(GetUsername(connection), "rank") + ", '-', " + Math.round(new Date().getTime() / 1000) + ", '" + db.escape(messageData.message) + "')", function (err, result) {
    console.log(result.insertId);
});
1
ekh On

As per the documentation, the first argument of the call back is error, and the second is the result.

You may also want to use placeholders for those dynamic values rather than concatenating them.

Moreover, do not hardcode single quote while using db.escape().

db.query("INSERT INTO table (`field1`, `field2`)
          VALUES ('Hello', " + db.escape("There") + ")",
         function(error, result) { });
0
Akram Saouri On

you need to replace

console.log(result.insertId); 

with

console.log(rows.insertId);

since it's the varibale you're passing to the callback function.