Why the length of result of MySQL query is not correct? The query is just count the number of message
column in database and print the length.
the code:
connection.query("SELECT COUNT(message) as total FROM `counter`", (err, results) => {
if(err) throw err;
console.log(results);
console.log("the length of result:", results.length);
the output:
[ RowDataPacket { total: 4 } ]
the length of result: 1
The correct length is 4
not 1
.
How to correct that, please?
results
contains the rows returned as an array. Since you're using SELECT COUNT(message)
, you're querying for the count of messages, which returns one row. This one row contains the result, which is an object of shape { total: 4 }
- where the total
comes from the as total
part of your SQL query.
To get the actual result, check that results.length > 0
and then you can access results[0].total
:
if (results.length > 0) {
console.log('Total:', results[0].total)
} else {
throw new Error('No results returned from query!')
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments