So, i seem to be having a problem with returning a value from my forEach MYSQL query loop in Node JS and then inserting this into an ejs template. Currently, these are my pieces of code:
app.js GET Request
app.get("/admin/stock", function(req, res) {
db.query("SELECT * FROM stock", function (err, stock) {
if (err) {
console.log("Error with showing SQL")
} else {
stock.forEach(function (stock) {
db.query("SELECT * FROM product WHERE productID = " +
stock.stock_productID, function (err, product) {
if (err) {
console.log("Error");
}
else {
stock.stock_productID = product[0].productName
}
});
db.query("SELECT * FROM currency WHERE currencyID = " +
stock.stock_currencyID, function (err, currency) {
if (err) {
console.log("Error");
}
else {
stock.stock_currencyID = currency[0].currencyName
}
});
db.query("SELECT * FROM customer WHERE customerID = " +
stock.stock_customerID, function (err, customer) {
if (err) {
console.log("Error");
}
else {
stock.stock_customerID =
customer[0].customerBusiness;
console.log(stock);
}
})
});
}
console.log(stock);
res.render("admin/stock", {stock:stock, userFName: req.user[1]})
})
});
Stock Page EJS
<table class="generalTable">
<tr>
<th>Product Name</th>
<th>Quantity</th>
<th>Currency</th>
<th>Cost</th>
<th>Date Bought</th>
<th>Bought From</th>
</tr>
<% stock.forEach(function(stock){ %>
<tr>
<td><%=stock.stock_productID%></td>
<td><%=stock.quantityStockCurrent%></td>
<td><%=stock.stock_currencyID%></td>
<td><%=stock.priceBought%></td>
<td><%=stock.boughtDate%></td>
<td><%=stock.stock_customerID%></td>
</tr>
<% }) %>
</table>
The First console.log of stock shows the replaced values, the second however, shows the original array values, and therefore the page is loaded in with the original values (IDs etc, instead of names).
How do I send the inner/edited array to the res.render instead of the original array?
Many Thanks, Brad
EDIT//////
By using JOINs, the output was correct
LEFT JOINandINNER JOINwork in SQL. Your code is the most inefficient way of retrieving information from a relational database. There is no use fixing this, please read about joins and rewrite your query.