0

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...

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

4
  • that's normal, because you are calling query() then logging from inside query, this will work, the log before the function call will return undefined because rows and fields are still undefined as query wasn't called to give them a value Commented Jun 9, 2022 at 9:20
  • if you can have the code to be await query(); and then after that log the rows, the rows should be defined now Commented Jun 9, 2022 at 9:22
  • could you explain how? I am new to the coding ..Do I have to await query(); when im calling the function or within a function? Commented Jun 9, 2022 at 9:27
  • 1
    Never mind, got it working! Thank you i've been having troubles with this whole day Commented Jun 9, 2022 at 9:28

1 Answer 1

1

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 query() 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

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

3 Comments

got it ! Thanks. Btw.one more question. my output in console is in this form: [ { plan: VIP } ] How to make the code output only VIP ?
if you are only expecting one output, u can simply index at 0 (the first output) so that would be rows[0].plan but if you are expecting more, you'll have to loop over the arrays (rows) to access every element on its own
Perfect! Works now. Can’t believe I didn’t try that first…

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.