0
   mysql.query('SELECT accountID,deviceID FROM EventData WHERE accountID = "'
       + acc
       + '" AND deviceID = "'
       + deviceID
       + '"  ORDER BY timestamp DESC LIMIT 1 ',
           function(err,rows,fields) {                   
               if (rows.length > 0) {                 
                   var accountID = rows[0].accountID;
                   var deviceID = rows[0].deviceID;
                   var re2 = ({
                       title: deviceID,                    
                   });                      
                   console.log(re2)
                   console.log("aaa")     
           }
    );

The above code produces the following output :

   [{ title: 'dev1'}]
   aaa
   [{ title: 'dev2'}]
   aaa

But I expected to see the following:

   [{ title: 'dev1'},
   { title: 'dev2'}]
   aaa

What am I doing wrong?

1
  • First off, please do not concatenate SQL query strings like that, use the placeholder syntax as it is more secure. Secondly, the code you've currently shown cannot produce the output you've shown, especially since re2 is not an array, it's an object. Commented Nov 8, 2014 at 14:51

1 Answer 1

1

You didn't even iterate through the rows, you just added the first title to re2.

This code should work:

mysql.query('SELECT accountID,deviceID FROM EventData WHERE accountID = ? AND deviceID = ? ORDER BY timestamp DESC LIMIT 1', [acc, deviceID],
       function(err,rows,fields) {
           if (rows.length > 0) { 
               var re2 = [ ];                    
               for (var i = 0; i < rows.length; i++) {
                   re2.push({ title: rows[i].deviceID });
               }                    
               console.log(re2);
               console.log("aaa")  ;
           }   
       }
);

Please note that I passed the parameters with placeholders instead of concatenate them explicitly to the string.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.