Soooo i'm trying to make an economy system, however, whenever I type the message "eco bal ${args}", which, the args is the name of the table, I get "undefined" as a result instead of "$0" which should be the balance I need to have. Here's the code.
client.on("message", message => {
if(message.author.bot) return;
const args = message.content.slice(config.prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
if (command === "testbal") {
const table = sql.prepare(`SELECT count(*) FROM sqlite_master WHERE type='table' AND name = '${args}';`).get();
if (!table['count(*)']) {
// If the table isn't there, create it and setup the database correctly.
sql.prepare(`CREATE TABLE IF NOT EXISTS ${args} (id TEXT PRIMARY KEY, user TEXT, guild TEXT, bal INTEGER);`).run();
// Ensure that the "id" row is always unique and indexed.
sql.prepare(`CREATE UNIQUE INDEX idx_${args}_id ON ${args} (id);`).run();
sql.pragma("synchronous = 1");
sql.pragma("journal_mode = wal");
}
// And then we have two prepared statements to get and set the score data.
client.getScore = sql.prepare(`SELECT * FROM ${args} WHERE user = ? AND guild = ?`);
client.setScore = sql.prepare(`INSERT OR REPLACE INTO ${args} (id, user, guild, bal) VALUES (@id, @user, @guild, @bal);`);
}
});
//Actual code of the thing
client.on("message", message => {
const args = message.content.slice(config.prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
if (command == "bal") {
if (message.author.bot) return;
let score;
if (message.guild) {
score = client.getScore.get(message.author.id, message.content.args);
if (!score) {
score = { id: `${message.guild.id}-${message.author.id}`, user: message.author.id, guild: message.guild.id, args, bal: 0}
}
score.bal++;
}
if (message.content.indexOf(config.prefix) !==0) return;
const data = sql.prepare(`SELECT bal FROM ${args}`);
message.channel.send(`You have ${data.bal}`)
}
});
When I run the command "eco bal", I get "You have undefined"
What is the difference between this:
const table = sql.prepare(`SELECT count(*) FROM sqlite_master WHERE type='table' AND name = '${args}';`).get();
and this:
const data = sql.prepare(`SELECT bal FROM ${args}`);
The first, table
, prepares and executes (get
) the sql. The second, data
only prepares the sql (i.e. creates a Statement
object).
The missing method ("fetch" if you will) is the proximate cause of the "You have undefined" result. If another data element will give the desired result, by all means try it!
Here's the API documentation on the Statement
object.