17

How can I check if no matching found in mysql (node.js)?

mysql.query("select * from table1 where name = 'abcd'", function(error, result, field) {
    if(error) {
        exist(error); //No error
    } else if(result) {
        console.log(result);  //displays '[]'
        exist(null, result);
    } else {
        exist(null, null); //It is never execute
    }
});
function exist(error, result) {
    if(result)
        console.log("Test:"+result); //Executed and displays 'Test:'
}

My database does not contains name = 'abcd'. So, how can I check if the query does not match?

Rodrigo Medeiros
  • 7,814
  • 4
  • 43
  • 54
Rejaul
  • 831
  • 1
  • 12
  • 35

1 Answers1

28

You're receiving an empty array ([]) as result of your query, because as you said, your database does not contain any row with name = 'abcd'.

When you do:

if (result) {
  if (result)
    console.log("Test:" + result);

, you'll enter the if, because JavaScript evaluates true for []. Take a look at this article here, that explains how JavaScript evaluates true and false values.

A better way to check if your result array is empty is to do:

if (result.length > 0) {
  if (result)
    console.log("Test:" + result);
greybeard
  • 2,249
  • 8
  • 30
  • 66
Rodrigo Medeiros
  • 7,814
  • 4
  • 43
  • 54