In node.js mysql query, check if no matching found

前端 未结 1 574
醉话见心
醉话见心 2020-12-31 08:22

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(         


        
相关标签:
1条回答
  • 2020-12-31 08:32

    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);
    
    0 讨论(0)
提交回复
热议问题