0

I'm using NodeJS and need to fetch an audioid field from my first MySQL query, assign it to a variable and use that variable in my next MySQL query. So I've tried to use;

var newaudioid = results[0].audioid;

But the result is coming back as "undefined".

Here's the code;

 connection.query(sql, [1, 2], function(err, results, fields){
    if (!err) {             
        res.send(JSON.stringify(results[0]) + JSON.stringify(results[1]));
        console.log(results[0]);
        console.log(results[1]);
        var newaudioid = results[0].audioid;
        console.log('newaudioid = ' + newaudioid);

    }  else {
        console.log('Error while performing query.');
        console.log(err);
    }
});

So console.log('newaudioid = ' + newaudioid); gives me back newaudioid = undefined

How can I fetch that audioid field from my first query?

7
  • 1
    Inspect results variable in debug session, probably there is some case issue? Commented Jun 14, 2021 at 9:35
  • How would I do that? Commented Jun 14, 2021 at 9:38
  • Try to log the value of result and see what it is returning. Commented Jun 14, 2021 at 9:38
  • What does the console.log(results[0]): return? Also, the res.send call is sending invalid JSON. Commented Jun 14, 2021 at 9:38
  • Yes if you could do a console.log(results) and post the result here so we can see if it is getting everything that is necessary, thanks. Commented Jun 14, 2021 at 9:39

1 Answer 1

1

Following up on your comment

SO I stringified IE: console.log('results0 = ' + JSON.stringify(results[0])); and got results0 = [{"audioid":144},{"audioid":147}]

Inside results[0] you have 2 objects that themselves have another object inside, and they both have the same property name. The problem is that javascript does not know which one you are referring to when you are saying results[0].audioid

What you can do is use [0] again to get the first one again, so that would be: results[0][0]

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

1 Comment

results[0][0].audioid to get the specific value

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.