I have 2 functions that I am using to access different columns in a single database based on a user ID. If the ID does not have a row in the database, I create a new row for that ID in the database. However when I call both these functions close together, the program ends up creating 2 new rows with the same ID, one for each data type.
exports.addXp = (id, amt) => {
db.get(`SELECT userId, xp FROM userData WHERE userId = ?`, [id], (err, row) => {
if (err) return console.error(err.message);
if (!row) {
db.run(`INSERT INTO userData (userId, xp) VALUES (?, ?)`, [id, amt], (err) => {
if (err) console.error(err.message);
});
} else {
db.run(`UPDATE userData SET xp = ? WHERE userId = ?`, [row.xp + amt, id], (err) => {
if (err) console.error(err.message);
})
}
});
}
exports.addBal = (id, amt) => {
db.get(`SELECT userId, bal FROM userData WHERE userId = ?`, [id], (err, row) => {
if (err) return console.error(err.message);
if (!row) {
db.run(`INSERT INTO userData (userId, bal) VALUES (?, ?)`, [id, amt], (err) => {
if (err) console.error(err.message);
});
} else {
db.run(`UPDATE userData SET bal = ? WHERE userId = ?`, [row.bal + amt, id], (err) => {
if (err) console.error(err.message);
})
}
});
}
I then call these with:
data.addXp(message.author.id, Math.floor(Math.random()*11 + 10));
data.addBal(message.author.id, Math.floor(Math.random()*3 + 3));
However, if the user ID does not exist in the database, then 2 rows end up being added, where one row has the user ID and the bal, and one row has the ID and the xp, instead of one row having all the values. How do I fix this?