Create a for loop within a MySQL query - mysql

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...

Related

Node.js updating column from array using loops

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;
}
}

Making custom sort in google script faster

I'm trying to organize a database by a rank in a certain order that I want. Normally, sort would work, but I want a couple of things to happen:
1. raw data so that filters can work for other data (i.e. by name, team, etc)
2. I don't want to always sort by rank
Ranks in order:
Captain, Officer, Chef, Crew, Recruit, Lost, Brig
Right now I'm forcing a filtered sort first alphabetically only when the rank filter is sorted, then when that is done, it sorts the list according to the above sort. The problem that I'm having is that it takes some time to execute the script. I'm thinking that this can be done much more efficiently, but I'm way rusty when it comes to this stuff. Here's my code below:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var members = ss.getSheetByName("Members");
var temp = ss.getSheetByName("sortRank");
var ranks = ["Captain", "Officer", "Chef", "Crew", "Recruit", "Lost", "Brig"];
var rankData = members.getRange(1,5,members.getLastRow(),1);
var search = null;
var query = null;
var x = null;
if(order != null) {
ranks = ranks.reverse();
}
for (var i=0; i < 7; i++) {
search = rankData.createTextFinder(ranks[i]);
x = search.findAll().length;
if(x != 0) {
query = search.findNext().getRow();
members.getRange(query,1,x,37).copyTo(temp.getRange(temp.getLastRow()+1,1));
}
}
}
Sort members by rank:
Assumes rank is in column 5 of members.
var members = ss.getSheetByName("Members");
var rankData = members.getRange(1,5,members.getLastRow(),1).getValues();
var ranks = ["Captain", "Officer", "Chef", "Crew", "Recruit", "Lost", "Brig"];
var rVal={};
ranks.forEach(function(e,i){rVal[e]=i+1;});
members.getDataRange().setValues(members.getDataRange().getValues().sort(function(a,b){return rVal[a[4]]-rVal[b[4]];}));

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?

How to perform a mysql statement with dynamic count of where clauses in java.sql

I have a jersey java server and a mysql server:
I send a POST with an ArrayList<Long> to the server. Then I want to do a select like ...where long OR long OR long....
Is there an elegant way to solve this problem and not to do always a single select in a for loop?
How can I form a sql-statement with dynamic count of where clauses?
Thank you very mutch.
Instead of OR multiple times, you can use IN with the where clause in the SQL query.
You can read ArrayList object in a loop and set the where clause values.
JAVA code snippet:
int paramCount = list.size();
StringBuilder sqlSelect = new StringBuilder( 1024 );
sqlSelect.append( "select x,y,z from my_table " );
if( paramCount > 0 ) {
sqlSelect.append( "where long_column in ( " );
for( i = 0; i < paramCount; i++ ) {
sqlSelect.append( ( i > 0 ? ", ?" : "?" );
} // for each param
sqlSelect.append( " )" );
} // if list is not empty
// make the prepare statement (pst) with the above sql string
// ...
// now set the parameter values in the query
int paramIndex = 1;
if( paramCount > 0 ) {
for( i = 0; i < paramCount; i++ ) {
pst.setLong( paramIndex++, ( (Long)list.get( i ) ).longValue() );
} // for each param
} // if list is not empty