【发布时间】:2019-08-27 08:48:53
【问题描述】:
我为一个不和谐的机器人编写了一个“购买”功能,它将项目的id 插入到 mysql 中的相应表中。
购买示例:
const join = args.join(" ")
let item = JSON.parse(fs.readFileSync('commands/economy/resources/items.json', "utf8"));
//Horses
const Horse1 = item.Horse1
//Buy Horse1
if (join === Horse1.name) {
let itemName = Horse1.name
let itemLuck = Horse1.luck
let itemId = Horse1.ID.toString()
let itemPrice = Horse1.price.toString()
//Account Check
if (rows.length < 1) { return message.channel.send("You do not have an account with The Iron Bank. Use ``;start`` to open one.") };
//Item Check
if (rows[0].horse === itemId) { return message.channel.send(`❌ | You already have a ${itemName}!`) }
//Money Check
if (rows[0].bank < itemPrice) { return message.channel.send(`You do not have enough coins in your account to buy **${itemName}**. It costs ${itemPrice} coins. You have ${rows[0].bank} coins`) };
//DB Update
con.query(`UPDATE economy SET horse = '${itemId}', horseluck = '${itemLuck}', bank = bank-${itemPrice} WHERE user = ${message.author.id}`)
//Bought
message.channel.send(`✅ | Purchased ${itemName} for ${itemPrice} coins.`)
};
长话短说,我需要从id: 中提取name: 并与rows[0].horse / rows[0].weapon 交叉引用它
这是我的 mySQL 选择查询中的代码:
//Direct to start if not in DB
if (rows.length < 1) {
return message.channel.send("You do not have an account with The Iron Bank. Use ``;start`` to open one.")
};
let horse = rows[0].horse;
let weapon = rows[0].weapon;
let armour = rows[0].armour;
let luck = (rows[0].horseluck + rows[0].weaponluck + rows[0].armourluck)
console.log()
return message.channel.send(`**Horse**: ${horse}\n**Weapon**: ${weapon ? weapon : "None"}\n**Armour**: ${armour ? armour : "None"}\n**Luck Bonus**: ${luck ? "+"+luck+"%" : "None"}`);
但上面打印出马的 ID 而不是 message.channel.send 中的名称。我如何将 MySQL 中的 ID 交叉引用到 JSON 中的 ID 并在 message.channnel.send 中打印出名称?
Example of my JSON file:
{
"Horse1":{
"ID": 1,
"name": "Dornish Sand Steed",
"description": "Splendid beasts",
"type": "Horses",
"price": "100000",
"luck": "5.0"
},
"Horse2":{
"ID": 2,
"name": "Arabian",
"description": "Preferred war mounts",
"type": "Horses",
"price": "50000",
"luck": "2.0"
},
"Weapon1":{
"ID": 1,
"name": "Longclaw",
"description": "Valyrian steel sword that was the ancestral weapon of House Mormont",
"type": "Weapons",
"price": "100000",
"luck": "5.0"
},
"Weapon2":{
"ID": 2,
"name": "Oathkeeper",
"description": "Valyrian steel sword made from House Starks greatsword",
"type": "Weapons",
"price": "50000",
"luck": "2.0"
},
}
(我知道这段代码中的 SQL 查询容易被 SQL 注入,这只是为了在我开始使用 mysql.format 之前进行测试)
【问题讨论】:
标签: javascript mysql node.js json discord.js