Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
passing data to function and using it node.js sql

I have this:

function afterCreateThePayment(req, res, rows) {

  for (var i = 0; i < rows.length; i++) {
    
    console.log(rows.length)
    var selecter = "SELECT * from SCHEDULE WHERE CLIENT_USERNAME = ? AND SESSION_STATUS = ?"
    //pass rows into this function
    mysqlconn.connect(function(err) {
          if (err) {
            console.error('Database connection failed: ' + err.stack);
            return;
          }
    
        mysqlconn.query(selecter, [rows[i]["USERNAME"], 'CONFIRMED'], async function(err, scheduleData) {
            if (err) {
                console.log(err);
            }
            

            for (var x = 0; x < scheduleData.length; x++) {
                console.log(scheduleData[x])
            }
            
            // mysqlconn.end();
        })
       
    })
   
}
} 

as you can see, i am passing rows into this function, and then trying to use rows[i]["USERNAME"] as one of the query parameters. However, when I do this, I get the error

TypeError: Cannot read property 'USERNAME' of undefined

so i am not sure what to do here, or if my logic is correct. could someone help?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Your issue is that he loop variable i is scoped to afterCreateThePayment. Keep in mind that var in javascript uses functional scoping, which is different than the block scoping you may be familiar with in C-style languages.

I am assuming that the callback from mysqlconn.connect is asynchronous. This means that the loop continues to execute, incrementing i. By the time the callback happens, the loop is out of bounds. If you peek at the value of i (not rows) in your callback you'll see what has happened.

Here is a similar example:

for (var i = 0; i < 5; i++)
{
  function internal()
  {
    console.log(i);
  }
  setTimeout(() => {internal();},1000);
}

The simplest option is swapping out the var i in your loop for let i. Making this change will make the i block scoped, so that the value will apply just to your current call to mysqlconn.connect. In my example, that's simply:

for (let i = 0; i < 5; i++)
{
  function internal()
  {
    console.log(i);
  }
  setTimeout(() => {internal();},1000);
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!