I am trying to assign MySQL query results in to a variable and then use it multiple times in script. I want to do this because I have PHP background and I like to work in this way. I know Node.js works asynchronously so this is my problem.
In the code below I want to assign MySQL results in to sql_results
variable but connection.query
function works asynchronously and code works in different order. In this case at the end of my code when I console.log(sql_results)
It returns me undefined
. This is normal because when I check console outputs I clearly see console.log(sql_results)
worked before console.log(results)
.
var mysql = require('mysql');
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "1234",
database: "db_progress"
});
var sql_query = "SELECT * FROM db_progress.tblresults res WHERE res.id < 3";
var sql_results; // This is my variable
connection.connect();
connection.query(sql_query, function (error, results, fields) {
if (error) throw error;
console.log(results); // This is mysql results
sql_results = results; // I am sure this works but I can't see
});
connection.end();
console.log(sql_results); // This returns undefined because works before query
How can I assign MySQL results in a variable, or If there is a different method for this purpose. Please explain in details.
Thanks.