Home > Net >  Cannot get specific information from a database using SQL
Cannot get specific information from a database using SQL

Time:04-18

it's my first time making two SQL requests in on 'connection.query' and something is definetly not right, first of all here is my code:

pool.getConnection(function (err, connection) {
    if (err) throw err;
    let sql = `SELECT * FROM custom_prefix WHERE guild_id = '12345678912345678'; SELECT * FROM cache_size`;
    connection.query(sql, async function (err, result) {
        if (err) throw err;
        console.log(result);
        connection.release();
    });
});

So far everything works perfectly fine and the output will be:

[
  [
    RowDataPacket {
      prefix: '!',
      guild_id: 12345678912345678,
      guild_name: 'server name',
      changed_by_id: 12345678912345678,
      changed_by_name: 'username#1234',
      changed_date: 2022-04-13T19:50:33.000Z
    }
  ],
  [ RowDataPacket { guilds: 4, users: 39 } ]
]

If I change the console.log(result) to console.log(result[1]) the output will be:

[ RowDataPacket { guilds: 4, users: 39 } ]

So everything works like I would expect it, but if I only want a specific value from the result[1], lets say the guilds, then I would do console.log(result[1].guilds).

I would to this because I have some other files where I check the database for something and use the result[0].something method and there it works absolutely fine. But as soon as I use two SELECT * FROM requests it doesn't.

So if I try to console.log the result[1].guilds the output will be:

undefined

Which makes no sense for me because I oftenly use this method and it works fine. But here it says undefined.

So I don't know how to get a specific value from one of the results when using two , I hope somebody here can help me. Thanks.

CodePudding user response:

Normally, a query result is an array of rows. However, since you performed multiple queries, result is an array of results of your queries; and each result is an array of rows returned by each query. Thus, you have one more level of nesting than in the scenario where you only have one query.

You are trying to get .guilds of an array, which does not have such a property. You want this instead:

result[1][0].guilds
  • Related