Node.js Discord.Js Mysql

Viewed 124

I'm creating a Discord bot. When we asked about an error, the bot gives an answer about that error. But when I get MySQL Data, i'm trying post it to Discord but it saying undefined.

Could you please help me?

const Discord = require("discord.js");
const client = new Discord.Client();
const ayarlar = require("./ayarlar.json");
const mysql = require('mysql');

var baglanti = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'hatabot'
});

baglanti.connect(function (err) {
  if (err) throw err;
    console.log("baglanti basarili")
client.on('message', msg => {

    baglanti.query("SELECT * from hatalar WHERE hata_komut LIKE "+'%'+msg.content+'%',function(err,sonuc){
 
      console.log(msg.content+" kelimesine ait\n\n"+sonuc+"\n\nsonucu bulundu");
    });
});
});


client.login(ayarlar.token)
1 Answers

Queries return arrays, so that is why plain result or in your case sonuc will return array, and for this reason won't work. Also it might have 0 results, so you need to check that first

baglanti.query("SELECT * FROM hatalar WHERE hata_komut LIKE "+'%'+msg.content+'%',function(err,sonuc){
     if(sonuc.length > 0){
     //Check if there is any rows
     console.log(sonuc[0].column);
     }
});

So to dive deeper;

As the query returns array, you need to choose which one of them, sonuc[0] is the first item in the array. The second thing I wrote there is the actual column of the table so let's say you have database with id, user, email columns and you want to display the user column, you would do sonuc[0].user

Related