Arnas Marnas Arnas Marnas - 1 year ago 88
MySQL Question

NodeJS mysql if null or empty

I have code, which should execute if the table is not in mysql or "NULL" or empty.

mysqlConnection.query('SELECT `something` FROM `here` WHERE `dog` = \'' +info+ '\'', function(err, row, fields) {
if(err) {
console.log('Error1');
return;
}
else if (!row.length) {
console.log('Error2');
return;
}
else if (row[0].something == 'NULL' || row[0].something == '') {
console.log('Error3');
return;
}
console.log('Works');
});


So the thing is, if "something" is not in mysql, console shows Error2, but if "something" is in mysql, but if its NULL, console shows Works, so whats the problem? Im checking if something is NULL, but it wont show Error3. If table is empty, it shows Error3. Thanks for help.

Answer Source

I would try something like this:

mysqlConnection.query('SELECT `something` FROM `here` WHERE `dog` = ?', [info] function(err, row, fields) {
  if(err) {
    return console.log('Error1');
  } else if (!row.length) {                                                   
    return console.log('Error2');
  } else if (!row[0].something) {
    return console.log('Error3');
  }

  console.log('Works');
});

It's using a "falsy" check for row[0].something which will return false if the value is undefined, null or an empty string. It also fixes the injection attack vector that t.niese mentioned.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download