Node.js updating column from array using loops - mysql

I have an amount array that is created from req.body.amount. If I want to update the 'amount' column of my table using the elements from the array, can I do it using a loop like this:
amount.forEach(function (value) {
let update = [value, req.body.name];
let updatequery = "UPDATE food_item SET amount = ? WHERE name IN (?)";
db.query(updatequery, update, (err, result) => {
if (err) throw err;
});
});
Do I also need another loop for the req.body.name array?

yea u have to create a nested loop if you have an array like this: arr[4][4]
it will give a table like this:
you can update columb as follows:
for(let i = 0; i < n; i++){
for(let j = 0; j < n; j++){
arr[i][j] = value;
}
}

Related

Nodejs Mysql Select Count nested loop insert query

I am new in nodejs and mysql.
I am have an array of objects that i get from post and want to insert it to mysql database.
If the data already exist then run the update query to database.
The problem is Insert query not loop the entire array. it just insert the last entry of Array. Here my code:
Array Data:
bukukasData
[{transactionid: '562018965521',
tanggal: '2018-06-05',
kodeakun: 0, item: 'Saldo',
debit: 100000, credit: 0,
saldo: 100000},
{transactionid:'562018595664',
tanggal:'2018-06-05',
kodeakun: 0,
item: 'Test Data',
debit: 0,
credit: 5000,
saldo:95000}]
NodeJS Query
app.post('/api/addbukukas', function(req, res) {
let bukukasData = req.body.bukukasData;
var status = '';
for (var i = 0; i < bukukasData.length; i++) {
var transactionid = req.body.bukukasData[i].transactionid;
var kodeakun = req.body.bukukasData[i].kodeakun;
var item = req.body.bukukasData[i].item;
var debit = req.body.bukukasData[i].debit;
var credit = req.body.bukukasData[i].credit;
var saldo = req.body.bukukasData[i].saldo;
var tanggal = req.body.bukukasData[i].tanggal;
db.query('SELECT COUNT (*) AS rowCount FROM bukukas WHERE transactionid = ?', [req.body.bukukasData[i].transactionid], function(error, result) {
var rows = result[0].rowCount;
if (rows > 0) {
db.query('UPDATE bukukas SET transactionid=?, kodeakun=?, tanggal=?, item=?, debit=?, credit=?, saldo=? WHERE transactionid = ?', [transactionid, kodeakun, tanggal, item, debit, credit, saldo, transactionid],
function(err, result) {
if (err) {
status = 'Update Gagal';
} else {
status = 'Update Success';
}
})
} else {
db.query('INSERT INTO bukukas (transactionid, kodeakun, tanggal, item, debit, credit, saldo) VALUES (?,?,?,?,?,?,?)', [transactionid, kodeakun, tanggal, item, debit, credit, saldo], function(err, insertresult) {
if (err) {
status = 'Insert Gagal';
} else {
status = "insertresult";
}
})
}
})
}
console.log(status);
return res.json({ status: status });
});
With this code the only data that getting inserted to database just the last data in array. How can i insert all the data in Array to database?
Thanks
Use let instead of var. That will avoid this problem.
The source of this problem is, that in JavaScript the for-loop loops through the variable i and starts bukukasData.length times the db query. The parameter is given as reference. Since the loop iterates very fast, the first sql statement ist started with i set to the last value and all db-statements are executed with i set to bukukasData.length. let was introduced to JavaScript to fix problems like this. With let it will create a copy of the variable in the background.

Create a for loop within a MySQL query

My query is:
connection.query("SELECT * FROM posts WHERE someId = 2", (err, rows) => {
allIds = [];
for(var i = 1; i <= rows.length; i++){
allIds.push(rows.id_post)
}
res.send("The IDs : " + allIds )
});
rows.length = 5, I'm getting the response: The IDs : , , , , ,. There is no data. I need all the IDs listed. Later want to run another query with those Ids, maybe in the same query but for now why aren't the IDs showing? What am I missing?
It seems like 'rows.id_post' is undefined. Are you sure there is a property named 'id_post'? Is rows a json or an array? If it's an array you need:
for(var i = 0; i < rows.length; i++){
allIds.push(rows[i].id_post)
}
This should answer your question.
for(var i = 1; i <= rows.length; i++){
allIds.push(rows.id_post)
}
You're not referencing the index of the rows results... I'm not familiar with the Node.JS syntax but I would think you need to reference the i row to get the value to push...

Nodejs loop through mysql Query give result = undefined

i have a Json Object and want to loop thorugh it. In my loop I want to execute a select query and save it result to another json Array.
So I start with a loop, performe a mysql query and want just log the results:
for (var x = 0; x < obj.length; x++) {
var query = connection.query('SELECT Id, date FROM tbl1 WHERE Id LIKE '+ mysql.escape(obj[x].ident) +'; SELECT Id, date FROM tbl WHERE Id LIKE '+ mysql.escape(obj[x].ident) +' ORDER BY date DESC Limit 1 offset 1', function (error, results, fields) {
if (error) {throw error;}
if (!error) {
console.log("resultset"+results); //<- Here I get the right result
console.log("ID: "+results[0].Id); //<- UNDEFINED
console.log("ID-LAST-entry: "+ results[1].Id); //<- UNDEFINED
} });
The Problem is that for booth results (0 and 1) i get = UNDEFINED.
Where is my mistake?
From the value of results, You can see that it is NOT an array of objects instead it is an array of arrays where each item is an object.
You need to iterate inner array to get the Id. See the snippet below. Parsing the result into JSON and then reads the required data.
if (!error) {
var parsedResults = JSON.parse(JSON.stringify(results));
var outerArraySize = parsedResults.length;
for (var outerIndex = 0; outerIndex < outerArraySize; ++outerIndex) {
var innerArraySize = parsedResults[outerIndex].length;
for (var innerIndex = 0; innerIndex < innerArraySize; ++innerIndex)
console.log("ID: " + parsedResults[outerIndex][innerIndex].Id);
}
}

Node mysql loop

Im currently doing this loop on Node.js using the MySQL package
var room_array;
var room_array_list = [];
var room_list = connection.query('SELECT * FROM rooms ORDER BY id', function(err, result) {
room_array = result;
for(var i = 0; i < result.length; i++)
{
var room_name = result[i].room_name;
var room_desc = result[i].room_desc;
var room_creator;
var room_owner = connection.query('SELECT username FROM users WHERE id = ? LIMIT 1', result[i].user_id, function(error, user) {
room_array_list.push({'name': room_name, 'desc': room_desc, 'owner': user[0].username});
});
}
console.log(room_array_list);
But when I try to log the room_array_list Im just getting an empty array [].
So my question is how should I do this loop process to form an array with the room_name, room_desc and owner values?

Passing a key-value array in NodeJS for MySQL select query

I can pass an array to an mysql insert in nodeJS like so..
var data = {userId: 3, name: "sample"}
db.query('insert into my_table SET ?', data, function(err, result){...}
Is there a similar way of passing an array to a select query in the where clause... without specifying all the fields?
var data = {userId: 3, name: "sample"}
db.query('select * from my_table WHERE ?', data, function(err, result){...}
Doesn't seem to work.. nor does using the SET name in place of where...
database.conn.config.defaultQueryFormat = function (query, values) {
if (!values) return query;
var updatedQuery = query.replace("?", function () {
var whereClause = "";
for(var index in values){
whereClause += mysql.escapeId(index) + " = " + db.escape(values[index]) + " and ";
}
whereClause = whereClause.substring(0, whereClause.length - 5);
return whereClause;
});
return updatedQuery;
};
This appears to work.. e.g.
var val = db.query('select * from my_table where ?', data, function(err, result) {
}