I am trying to get data from a MySQL database using node.js. Then I want to append that data to an object so I can later use it to make an HTML table.
This is my module code:
var mysql = require("mysql");
var date = require("dateformat");
var results = {}
exports.data = function ()
{
var conn = mysql.createConnection({
host: "localhost",
user: "admin",
password: "myphpadmin",
database: "tests"
});
conn.connect(function (err) {
if (err) throw err;
conn.query("SELECT Id, Description, Date, Amount, Merchant, Type, Sub, Source FROM main", function (err, result, fields) {
if (err) throw err;
else append(result);
});
});
function append(result) {
for (i = 0; i > result.length; i++) {
id = result[i].Id;
des = result[i].Description;
date = dateFormat(result[i].Date, "mmmm d, yyyy");
a = result[i].Amount;
m = result[i].Merchant;
t = result[i].Type;
sub = result[i].Sub;
s = result[i].Source;
data = {"Id": id, "Des": des, "Date": date, "A": a, "M": m, "T": t, "Sub": sub,"S": s}
results.push(data)
}
}
return results
}
This is my main file which I run...
var data = require('./data')
console.log(data.data())
When I run:
node tests.js
it shows: {}
Any idea why?
I am using Node.js(Version: 14.15.4) on a windows 10 computer. I can give more details if needed!
results = { ...data }you have completed your first round in the loop. But you want to avoid that the next rounds of the loop overwrites the data from the previous. One way is to save each round as a new object with a unique name. You can do that by including the start 'results' object inside the loop and assigning the iterator [i] to it so you get results1, results2, results3, etc. and thus avoid overwriting anything. Afterwards you take each object and insert separately into your table.