Search code examples
node.jsnode-mysql

Values of the results object is null when quering a database in node.js


So I'm trying to query a record from a database and then put it into xml format in node.js. The programname is the primary key of the sasinfo table, so it's guaranteed that I'll only be working with one record. The problem is that when I run the code below, console.log(messagetoclient) prints this:

<messagetoclient><programname>undefined</programname><comment>undefined</comment><guid>undefined</guid></messagetoclient>

However, console.log(results) prints the this (the correct values from the record):

[ { programname: 'helloworld', comment: 'testing', GUID: '9b23e0f7b7da4535b99f706301539a44' } ]

Could someone help me figue out why the values of the key value pairs aren't being printed? Thanks.

 query2 = connection.query('SELECT * FROM sasinfo WHERE programname = ?', [programname], function(err, results) {
              if(err){
                           console.log(err);
                    }
              else{
                    console.log(results);
                    messagetoclient= '<messagetoclient><programname>'+results.programname+'</programname><comment>'+results.comment+'</comment><guid>'+results.GUID+'<guid></messagetoclient>';
                    console.log(messagetoclient);
               }
            });

Solution

  • Try

    messagetoclient= '<messagetoclient><programname>'+results[0].programname+'</programname><comment>'+results[0].comment+'</comment><guid>'+results[0].GUID+'<guid></messagetoclient>';
    

    since results is an array.