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:
According to this documentation, it must work. Where's my mistake? Thanks in advance.
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./mysqljs/mysql#getting-the-id-of-an-inserted-row
According to this documentation, it must work. Where's my mistake? Thanks in advance.
Share Improve this question asked Jul 4, 2016 at 14:00 ReeseReese 2531 gold badge5 silver badges15 bronze badges 2- Do you have an autoincrement column? – fedorqui Commented Jul 4, 2016 at 14:02
- you should have an error-first callback – Adam Commented Jul 4, 2016 at 14:03
3 Answers
Reset to default 2you need to replace
console.log(result.insertId);
with
console.log(rows.insertId);
since it's the varibale you're passing to the callback function.
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);
});
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) { });