Reputation: 287
var sender_username = req.session.user_id;
var recipient_username = req.body.recipient_username;
var content = req.body.content;
var sql = ' SELECT sender_username, recipient_username, COUNT(recipient_username) as count FROM message WHERE sender_username = "'+sender_username+'" AND recipient_username = "'+recipient_username+'" GROUP BY sender_username LIMIT 1 ';
var message_no = 0;
var data;
connection.query(sql, function(err, result) {
if (err) {
res.send(err);
}
else {
data = result;
// res.send(data); < - this works
// res.send(result); <- this works
// res.send(result.count); <- undefined
}
});
res.send(data); // undefined (can't seem to save to variable after connection.query())
The res.send(result);
seems to work. It gives:
[{"sender_username":"sender","recipient_username":"recipient","count":2}]
I am just trying to get the value for count
and save that to a variable, but things like result.count
are returning undefined for some reason.
Upvotes: 0
Views: 41
Reputation: 45500
It's because the JSON is an array, so you should access it like the following
res.send(result[0].count);
Upvotes: 1