I am trying to run a MySQL query in Javascript and return the value of the row but the function return keeps coming back as undefined. Can someone help me figure out what i am missing?
/** Start Write to CSV file ################################################################# */
function writeToCSVFile(data) {
let file = "c:/temp/" + "theFileName" + "_report.csv";
fs.writeFileSync(file, data, { flag: "a+" });
}
/** End Write to CSV file ################################################################# */
/** Start Query ######################################################################### */
function runQuery(query, id) {
mysqlConnection.query(query + id, (err, rows, fields) => {
if (!err) {
console.log(rows);
let data = rows[0].user_email;
return data;
} else {
console.log("Error: " + err);
}
});
}
/** End Query ######################################################################### */
/** Start Email Query ######################################################### */
function getEmail(currentId) {
var currentEmail = runQuery(
"SELECT user_email FROM fakeDatabase.wp_users WHERE ID = ",
currentId
);
console.log("Current Email: " + currentEmail);
return currentEmail;
}
/** End Email Query ######################################################### */
/** Loop that calls the main getEmail function /
const ids = ["6209", "3467"];
for (const currentId of ids) {
let email = getEmail(currentId);
writeToCSVFile(email);
}
I am expecting that once the data is pulled from the query the function returns it to the loop to be writen to the CSV file.