Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL output undefined when using it outside the function

I am trying to execute SQL results outside it’s function.
This is my code:

    
var rows;
var fields;
    const connection = await mysql.createConnection({
     host: 'localhost',
      user: 'root',
      password: '',
      database: 'root'
    });

    connection.connect((err) => {
          if(err) {
             console.log(err);
             process.exit(0);
          }
        
            console.log('logged in!');        
    });

            async function query() {
                 [rows, fields] = await connection.execute("SELECT plan FROM users WHERE username = 'onyx'");
                   console.log(rows);
                 
 
 }
 console.log(rows);
 query();

First console.log(rows); gives correct output but once I put it outside the function, i get error undefined.

I know there are questions about this but I need better understanding and explanation about this…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am using sync now as told but still same problem.

>Solution :

You have an async function query() and you are trying to log ‘rows’ inside and outside the function,
according to your code, you have

console.log(rows);
query();

this way, the log inside the function will surely return an output because it is being filled by the query above it, but if u try to log outside, it will not and that’s because u didn’t await qeury() to finish.

to get it working:

await query();
console.log(rows)

this way, rows will be filled before logging because you are filling rows with an async function which has to be awaited

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading