2

I have trouble figuring out how to get the data from mysql Queries in the callback function. For example I have the query as follows:

mysqlConnection.query('SELECT COUNT(*) from card AS count', function (err, result) {
    if (err) {
        throw err;
    } 
    else {
        console.log(Type.of(result));
        console.log("card count is as: " + result.count);
        console.log("Card count is: " + result["COUNT(*)"]);
        console.log(result);
    }
});

This prints out:

[Function: Array]
card count is as: undefined
Card count is: undefined
[ { 'COUNT(*)': 3 } ]

What is a "[Function: Array]" datatype and how do you pick variables from it? An array of functions? Why is "result.count" undefined even though I in the query I use the AS thing.

Also how is the following query different from the one below it?

mysqlConnection.query('SELECT COUNT(*) from card AS count', function (err, rows, fields) {
});

mysqlConnection.query('SELECT COUNT(*) from card AS count', function (err, result) {
});

When do I use the other and when the other one?

2 Answers 2

3

The callback with function (err, rows, fields) is much more appropriate for selecting data you are working with, and rows will then be populated by an array of arrays. So, in your case rows[0]['COUNT(*)'] would be your count.

For selects with multiple rows, you can loop through the results.

As a side note, I think you meant SELECT COUNT(*) AS count from card which would then be accessible much more simply as rows[0].count

Sign up to request clarification or add additional context in comments.

Comments

2

Change your query to

SELECT COUNT(*) AS count from card 

The column alias should be defined after selecting the column, not after the from.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.