Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
123
rated 0 times [  125] [ 2]  / answers: 1 / hits: 49847  / 10 Years ago, thu, july 10, 2014, 12:00:00

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?


More From » mysql

 Answers
13

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);

[#70252] Tuesday, July 8, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckaylab

Total Points: 311
Total Questions: 120
Total Answers: 93

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
;