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?
Related
function myFunction() {
var ServerIP = 'xxx.xxx.xxx.xxx';
var SQL_Port = '3306';
var SQL_Usr = 'GDriveUser';
var SQL_Pwd = '**********';
var SQL_DB = 'wordpress_10';
var connectorInstance = 'jdbc:mysql://' + ServerIP+':'+SQL_Port;
var ConnectString = connectorInstance+'/'+SQL_DB;
var conn = Jdbc.getConnection(ConnectString, SQL_Usr, SQL_Pwd);
conn.setAutoCommit(false)
var SQLstatement = conn.createStatement();
var result = SQLstatement.executeQuery("SELECT * FROM `TABLE35` WHERE Team in ( 'atl', 'bkn', 'bos', 'cha', 'chi', 'cle', 'dal', 'den', 'det', 'gsw') and Date > 20201201 ORDER BY Date ASC");
var ss = SpreadsheetApp.openById("1QTv67oSTYnwsD0kwd0sDubzAor19pfAVngubjePqtzJg");
var sheet = ss.getSheetByName("Imported");
var cell = sheet.getRange('A2');
// loop through result object, setting cell values to database data
var row = 0;
while(result.next()) {
for(var i=0; i<23; i++) { // four fields per record
cell.offset(row, i).setValue(result.getString(i+1));
}
row++;
}
result.close();
SQLstatement.close();
conn.close();
}
This Google Script is only putting about 150 rows into my Google Sheet and then it times out.
Can someone help me find a fix for this?
Something like this:
function myFunction() {
var ServerIP = 'xxx.xxx.xxx.xxx';
var SQL_Port = '3306';
var SQL_Usr = 'GDriveUser';
var SQL_Pwd = '**********';
var SQL_DB = 'wordpress_10';
var connectorInstance = 'jdbc:mysql://' + ServerIP+':'+SQL_Port;
var ConnectString = connectorInstance+'/'+SQL_DB;
var conn = Jdbc.getConnection(ConnectString, SQL_Usr, SQL_Pwd);
conn.setAutoCommit(false)
var SQLstatement = conn.createStatement();
var result = SQLstatement.executeQuery("SELECT * FROM `TABLE35` WHERE Team in ( 'atl', 'bkn', 'bos', 'cha', 'chi', 'cle', 'dal', 'den', 'det', 'gsw') and Date > 20201201 ORDER BY Date ASC");
var ss = SpreadsheetApp.openById("1QTv67oSTYnwsD0kwd0sDubzAor19pfAVngubjePqtzJg");
var sheet = ss.getSheetByName("Imported");
var cell = sheet.getRange('A2');
// loop through result object, setting cell values to database data
var row = 0;
let oA=[];
sheet.getRange(2,1,sheet.getLastRow()-1,sheet.getLastColumn()).clearContent();//clear content before writing
while(result.next()) {
let rA=[];
for(var i=0; i<23; i++) {
rA.push(result.getString(i+1));
}
oA.push(rA);
}
sheet.getRange(2,1,oA.length,oA[0].length).setValues(oA);//starts at row 2 every time
result.close();
SQLstatement.close();
conn.close();
}
I’m trying to automate work routines with google forms, php and mysql. I did the following software architecture.
There is the form named as S, it is the static one, since I created it manually using GUI. Form Sform has the form submit trigger which puts data into the my mysql database.
After that data is processed by the php script which finally calls google script, which is published as a web application.
This script gets get parameters and parses them, gets new processed data from my database and programmatically builds forms depending on the selected data, finally it adds a trigger to dynamically (programmatically) created form or forms (let's name them as Dform).
The problem is that the function FormApp.getActiveForm() which is coded in the trigger of programmatically created form returns form id of the static form (which is manually created).
Here the code of static form Sform submit trigger:
function SaveData() {
var form = FormApp.getActiveForm();
var formResponses = form.getResponses();
var formResponse = formResponses[formResponses.length-1];
var email = formResponse.getRespondentEmail();
var itemResponses = formResponse.getItemResponses();
var workDay = null;
var workFiles = null;
for (var j = 0; j < itemResponses.length; j++) {
var itemResponse = itemResponses[j];
if (itemResponse.getItem().getTitle() == 'Pick the date of files you uploading') {
workDay = itemResponse.getResponse().toString();
}
if (itemResponse.getItem().getTitle() == 'Choose log files to be uploaded') {
workFilesIds = itemResponse.getResponse();
}
}
var dbUrl = '...';
var user = '...';
var userPwd = '...';
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
var stmt = conn.prepareStatement('select worker_id from in_workers where worker_name = ?');
stmt.setString(1, email);
var results = stmt.executeQuery();
var worker_id = -1;
while (results.next()) {
worker_id = results.getString(1);
}
results.close();
if (worker_id == -1) {
stmt = conn.prepareStatement('INSERT INTO in_workers '
+ '(worker_name) values (?)', 1);
stmt.setString(1, email);
stmt.executeUpdate();
var res = stmt.getGeneratedKeys();
res.beforeFirst();
res.next();
worker_id = res.getInt(1);
}
var fName = '';
var fBlob = new Array(workFilesIds.length);
for (var j = 0; j < workFilesIds.length; j++) {
var file = DriveApp.getFileById(workFilesIds[j]);
fName = fName + '\n\r' + file.getName();
fBlob[j] = file;
stmt = conn.prepareStatement('INSERT INTO test_dep_files '
+ '(worker_id, file_name, file_date, file_body) values (?, ?, ?, ?)');
stmt.setString(1, worker_id);
stmt.setString(2, file.getName());
stmt.setDate(3, Jdbc.parseDate(workDay));
stmt.setBytes(4, file.getBlob().getBytes());
stmt.executeUpdate();
}
conn.close();
GmailApp.sendEmail('...', 'Control workplace form completed'
, 'User ' + email + ' uploaded data on ' + workDay
+ ' file list: ' + fName,
{attachments: fBlob, name: fName});
}
Here the code of script published as web application:
function doGet(e) {
var worker_id = e.parameter['worker_id'];
var form_trig_func_name = e.parameter['form_trig_func_name'];
var dbUrl = '...';
var user = '...';
var userPwd = '...';
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
stmt = conn.prepareStatement('select form_id from in_workers where worker_id = ?');
stmt.setString(1, worker_id);
var results = stmt.executeQuery();
var form_id;
results.beforeFirst();
while (results.next()) {
form_id = results.getString(1);
}
results.close();
var form;
try {
form = FormApp.openById(form_id);
var items = form.getItems();
var l = items.length;
for (var j = 0; j < l; j++) {
form.deleteItem(0);
}
} catch (e) {
form = FormApp.create('Enter additional products data');
}
stmt = conn.prepareStatement('select fc_id, fc_name_sys, fc_date from test_dep_fc t1'
+ ', test_dep_files t2 where t1.file_id = t2.file_id and fc_name_real is null '
+ 'and worker_id = ?');
stmt.setString(1, worker_id);
var results = stmt.executeQuery();
results.beforeFirst();
while (results.next()) {
form.addTextItem()
.setTitle(results.getString(2) + ' от ' + results.getString(3))
.setHelpText(results.getString(1));
}
results.close();
form_id = form.getId();
var allTriggers = ScriptApp.getUserTriggers(form);
var l = allTriggers.length;
for (var i = 0; i < l; i++)
ScriptApp.deleteTrigger(allTriggers[i]);
allTriggers = ScriptApp.getProjectTriggers();
l = allTriggers.length;
for (var i = 0; i < l; i++) {
if (allTriggers[i].getHandlerFunction() === 'saveData' + form_trig_func_name) {
ScriptApp.deleteTrigger(allTriggers[i]);
}
}
ScriptApp.newTrigger('saveData'+form_trig_func_name)
.forForm(form)
.onFormSubmit()
.create();
var form_url = form.getPublishedUrl();
stmt = conn.prepareStatement('update in_workers set form_id = ?, form_url = ? where worker_id = ?');
stmt.setString(1, form_id);
stmt.setString(2, form_url);
stmt.setString(3, worker_id);
stmt.execute();
conn.close();
return HtmlService.createHtmlOutput(form_id + '\n\r' + form_trig_func_name);
}
This is the code of dynamically (programmatically) created forms Dforms:
function saveData2() {
var form = FormApp.getActiveForm();
var formResponses = form.getResponses();
var formResponse = formResponses[formResponses.length-1];
var itemResponses = formResponse.getItemResponses();
var dbUrl = '...';
var user = '...';
var userPwd = '...';
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
var fc_names_real = '';
var fc_ids = '';
var fc_names_sys = '';
for (var j = 0; j < itemResponses.length; j++) {
var itemResponse = itemResponses[j];
var fc_id = itemResponse.getItem().getHelpText();
var fc_name_sys = itemResponse.getItem().getTitle();
var fc_name_real = itemResponse.getResponse().toString();
fc_names_real = fc_names_real + ' ' + fc_name_real;
fc_ids = fc_ids + ' ' + fc_id;
fc_names_sys = fc_names_sys + ' ' + fc_name_sys;
stmt = conn.prepareStatement('update test_dep_fc '
+ 'set fc_name_real = ? where '
+ 'fc_id = ?');
stmt.setString(1, fc_name_real);
stmt.setString(2, fc_id);
stmt.executeUpdate();
}
conn.close();
GmailApp.sendEmail('...', 'Control workplace form2 completed'
, 'Product serial nums: ' + fc_names_real
+ '\n\rProducts sys nums: ' + fc_names_sys
+ '\n\rProducts ids: ' + fc_ids
);
}
function saveData3() {
the same code as for saveData2
}
function saveData4() {
the same code as for saveData2
}
function saveData5() {
the same code as for saveData2
}
...
So the problem is that in saveData2 first code instruction returns wrong form id. It always returns form id of Sform.
Please help me with this, I'm ready to think that I have found a google forms bug.
Thanks a lot, Yaroslav
EDIT 1
hi #tehhowch, thank you, I did try, but, unfortunately, following code
function saveData2(e) {
//var form_id = e.source.getId();
...
returns wrong form id as well, it returns Sform id.
Finally this issue was solved next day it was written here. The solution is as simple as it is stupid one.
In the script published as web application code I add following instructions after form creation code. I save trigger function name to its properties.
PropertiesService.getDocumentProperties().setProperty(
'saveData'+form_trig_func_name, form_id);
Code to dynamically (programmatically) create forms Dforms was rewritten. When corresponding trigger fires I just take a formId in earlier saved property value.
function saveData2(e) {
//var form_id = e.source.getId();
var form_id = PropertiesService.getDocumentProperties().getProperty('saveData2');
saveDataAll (form_id, 2);
}
function saveData3() {
var form_id = PropertiesService.getDocumentProperties().getProperty('saveData3');
saveDataAll (form_id, 3);
}
function saveData4() {
var form_id = PropertiesService.getDocumentProperties().getProperty('saveData4');
saveDataAll (form_id, 4);
}
function saveData5() {
var form_id = PropertiesService.getDocumentProperties().getProperty('saveData5');
saveDataAll (form_id, 5);
}
function saveData6() {
var form_id = PropertiesService.getDocumentProperties().getProperty('saveData6');
saveDataAll (form_id, 6);
}
function saveData7() {
var form_id = PropertiesService.getDocumentProperties().getProperty('saveData7');
saveDataAll (form_id, 7);
}
function saveData8() {
var form_id = PropertiesService.getDocumentProperties().getProperty('saveData8');
saveDataAll (form_id, 8);
}
function saveData9() {
var form_id = PropertiesService.getDocumentProperties().getProperty('saveData9');
saveDataAll (form_id, 9);
}
function saveData10() {
var form_id = PropertiesService.getDocumentProperties().getProperty('saveData10');
saveDataAll (form_id, 10);
}
function saveData11() {
var form_id = PropertiesService.getDocumentProperties().getProperty('saveData11');
saveDataAll (form_id, 11);
}
function saveDataAll (form_id, saveData)
{
var form = FormApp.openById(form_id);
...
I have not more then ten users of this functional and such workaround works for me. So the problem is closed.
<script>
$("#addopdfrm").submit(function(){
var opdname = $("#opdname").val();
var opdsex = $("#opdsex").val();
var opdage = $("#opdage").val();
var opdaddress = $("#opdaddress").val();
var opdcity = $("#opdcity").val();
var opdstate = $("#opdstate").val();
var opdpin = $("#opdpin").val();
var opdcon = $("#opdcon").val();
var opdmail = $("#opdmail").val();
var opdpresfee = $("#opdpresfee").val();
var odate = new Date();
var opdmonth = odate.getMonth()+1;
var opdyear = odate.getFullYear();
var opdday = odate.getDate();
var opddate = opdday+"/"+opdmonth+"/"+opdyear;
var opdtime = Date.now();
var mysql = require('promise-mysql');
var connection;
mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'plasmadoc'
}).then(function(conn){
connection = conn;
return connection.query("INSERT INTO `opdrec` VALUES('', '"+opdname+"', '"+opdage+"', '"+opdsex+"', '"+opdcon+"', '"+opdaddress+"', '"+opdpin+"', '"+opdcity+"', '"+opdstate+"', '"+opdmail+"', '"+opddate+"', 'no', '"+opdtime+"')");
}).then(function(rows){
var result = connection.query("INSERT INTO `opdvisits` VALUES('"+rows.insertId+"', '"+opddate+"', 'Prescription Fee', '"+opdpresfee+"', 'Waiting', 'no', '"+opdtime+"')");
connection.end();
return result;
}).then(function(rows){
// Logs out a ring that Frodo owns
alert("New Record Added");
});
});
</script>
I want to execute the first query. Retrieve the id of inserted row which is auto increment primary key and then use that id to insert data in different table.
Only the first query is executing. The second query is not executing. please help
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);
}
}
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) {
}