'Creating a profile in mySQL database and using it right after to display what's inside it Discord.js
I'm creating my Discord bot, and I saw that with the hosting provider I bought came with a mySQL database, so I'm using it. I connected to it with the mySQL NPM package:
export const con = mysql.createConnection({
host: process.env.MYSQL_HOST,
port: process.env.MYSQL_PORT,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DB,
});
and it works fine. I created a table in the database, with 3 parameters:id: Discord user idbananas: My toy currencydeposit: The currency deposit
I set it up that on the interactionCreate event, whenever a user uses an interaction, it checks the database, if there is a profile, it does nothing, else, it creates the profile in the database. Code:
async checkDB(int: CommandInteraction | MessageComponentInteraction) {
await con.query(
`SELECT * FROM profileSchema WHERE id = '${int.user.id}'`,
async (e: Error, rows: any) => {
if (e) throw e;
if (!rows[0]) {
await con.query(
`INSERT INTO profileSchema (id, bananas, deposit) VALUES ('${int.user.id}', 100, 0)`
);
}
}
);
},
this code works fine, the problem is that if a user does not have a profile in the database, and they use a currency related command, like the one that shows their balance, the bot crashes because their credits in the database result nonexistent, even though the profile gets created and the second time they use the command it works properly! How can I code so that if the user is not in the database and uses a command, it creates and displays at the same time? Here's the code that checks the currency balance:
await con.query(
`SELECT * FROM profileSchema WHERE id = ${interaction.user.id}`,
async (e: Error, rows: any[]) => {
if (e) throw e;
let wallet: {
bananas: number;
deposit: number;
};
try {
wallet = {
bananas: rows[0].bananas,
deposit: rows[0].deposit,
};
} catch (e) {
throw e
return;
}
)
Solution 1:[1]
So unless it is really needed, you don 't need the async/await components in this but the simple answer you are looking for is to change if (!rows[0]) to if (!rows.length) but that works when you set up your query like such:
con.query(`SELECT * FROM profileSchema WHERE id = '${int.user.id}'`, (err, rows) => {
if (err) throw err;
if (!rows.length) {
con.query(`INSERT INTO profileSchema (id, bananas, deposit) VALUES ('${int.user.id}', 100, 0)`, (err) => {
if (err) throw err;
});
} else {
let wallet = {
bananas: rows[0].bananas,
deposit: rows[0].deposit,
}
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gh0st |
