I am trying to detect when nodejs receives no data back from a mysql query. If the data that is put through a GET request is correct, it gives back the desired results.
Working Request:
http://server.com:8000?a=userinfo&user=datathatmatchesvalueindb
Non-Working Request
http://server.com:8000?a=userinfo&user=datathatdoesn'tmatchanythinginthedb
By non-working, I mean if the request includes data that is not in the mysql table, it displays a blank white page, instead of the desired result of 'no data'.
In PHP if you want to detect if there is no data in the mysql row, you can do the following:
if($res->num_rows === 0)
{
echo 'no data';
} else {
//Do you functions here
}
Is there an equivalent for nodejs code?
Here is the code I have written:
var express = require('express');
var app = express();
var database = require('mysql-simple');
app.get('/', function(req, res){
database.init('user', 'pass', 'db', 'IP');
var data = '';
if (req.query.a == 'userinfo') {
var q = 'SELECT * FROM `addrbook` WHERE `key` =\''+req.query.user+'\'';
} else if (req.query.a == 'facebook') {
var q = 'SELECT * FROM `addrbook` WHERE `facebook` =\''+req.query.fb+'\' OR `facebookp` =\''+req.query.fb+'\'';
} else if (req.query.a == 'youtubeurl') {
var q = 'SELECT * FROM `addrbook` WHERE `youtubeurl1` =\''+req.query.url+'\' OR `youtubeurl2` =\''+req.query.url+'\' OR `youtubeurl3` =\''+req.query.url+'\'';
} else {
var q = 'SELECT * FROM `addrbook` WHERE `key` =\''+req.query.user+'\'';
}
database.query(q, function(err, rows, fields)
{
if (err) {
console.log('error fetching user data: ' + err);
return;
}
//console.log(results);
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if(rows.length > 0) {
var key = row['key'];
var fb = row['facebook'];
var daddr = row['addr'];
if (req.query.a == 'userinfo') {
data = JSON.stringify(row);
res.write(data);
} else if (req.query.a == 'facebook') {
data = JSON.stringify(daddr);
res.write(data);
} else if (req.query.a == 'youtubeurl') {
data = JSON.stringify(daddr);
res.write(data);
} else {
res.write('no data');
}
} else {
res.write('no data');
console.log('no data');
}
}
res.end();
});
});
app.listen(8000);
res.send()to get data out, and callnext()to keep the response chain going.