I'm trying to get a variable out of a query as shown below, thanks in advance
var deutsch_meund_note = "";
connection.query(
'SELECT count(*) as sum FROM noten WHERE id = ? and fach = ?',
[id, "mathe"],
function(error, results, fields) {
if (error) {
console.log("no deutsch_schr for id: "+ id);
} else {
const deutsch_meund_viel = results[0].sum;
connection.query(
'SELECT SUM(note) as sum FROM noten WHERE id = ? and fach = ?',
[id, "deutsch_meund"],
function(error, results, fields) {
const deutsch_meund_insge = results[0].sum;
const deutsch_meund_note = deutsch_meund_insge / deutsch_meund_viel;
//this variable: **var deutsch_meund_note = deutsch_meund_note;**
});
}
});
I need to get the variable out of the "connection.query" function but when I try it like the example above it just says "undefined"
Related
I want to have this particular method return the accoount type (acc_type) as well as account number (accnumber)
I have written this code, but i need to return those parameters. Very new to this, kindly help.
app.post('/api/create-account', function (req, res) {
var prologue = '00345';
var digits = Math.floor(Math.random() * 900000) + 100000;
var accnumber = prologue + digits;
var firstname = req.body.firstname;
var lastname = req.body.lastname;
var fullname = firstname + ' ' + lastname;
var acc_type = req.body.acc_type;
var address = req.body.address;
var telephone = req.body.telephone;
var email = req.body.email;
var birth_date = req.body.birth_date;
var gender = req.body.gender;
var bvn_number = req.body.bvn_number;
dbConn.query('insert into fdsh_demobank (firstname, lastname, address, telephone, email,birth_date, gender,bvn_number, acc_type,accnumber ) values (?,?,?,?,?,?,?,?,?,?)', [firstname, lastname, address, telephone, email, birth_date, gender, bvn_number, acc_type, accnumber], function (error, results, fields) {
if (error) throw error;
return res.status(200).send({ error: false, data: results, message: 'created' });
});
sendConfirmationEmail(fullname, accnumber, acc_type, email);
sendOnboardingEmail(fullname, email);
})
been checking out and its not giving me the adequate results.
Edits
I am trying to do a SELECT statement here , says I have error on my SQL Syntax. on the SELECT * from area.
Please see the code below
app.get('/api/get-customer/:email', function (req, res) {
var email = req.params.email;
dbConn.query('select * from fsdh_demobank where email is = ?', [email], function (error, results, fields) {
if (error) throw error;
return res.status(200).send({ error: false, data: results[0], message: 'customer data' });
})
})
app.post('/transfer', (req,res) => {
db.query('SELECT * FROM bank.user_info where acc_no = ?',
[req.body.from],(err, result) => {
if(err){
res.send({err: err,id: 0});
}else{
if(req.body.Amount>result[0].acc_bal){
res.send({err: "Insufficient Balance !!!",id: 1})
return 0;
}else{
const senderNew = {};
senderNew.amount = req.body.Amount;
senderNew.transaction = 'sent';
senderOld.push(senderNew);
const freshSend = JSON.stringify(senderOld);
const senderBal = result[0].acc_bal-req.body.Amount;
db.query('UPDATE user_info SET transactions = ?, acc_bal = ? WHERE acc_no = ?',
[freshSend, senderBal, req.body.from], (err,result) => {
if(err){
res.send({err: err,id: 2})
}else{
db.query('SELECT * from user_info WHERE acc_no = ?',
[req.body.to], (err, result) => {
if(err){
res.send({err: err,id: 3});
}else{
const receiverOld = JSON.parse(result[0].transactions);
const receiverNew = {};
receiverNew.amount = req.body.Amount;
receiverNew.transaction = 'received';
receiverOld.push(receiverNew);
const freshReceive = JSON.stringify(receiverOld);
const receiverBal = parseInt(result[0].acc_bal) + req.body.Amount;
db.query('UPDATE user_info SET transactions = ?, acc_bal = ? WHERE acc_no = ?',
[freshReceive, receiverBal, req.body.to], (err, result) => {
if(err){
res.send({err: err,id: 4});
}else{
db.query('SELECT * FROM user_info WHERE acc_no = ?',
[req.body.from], (err, final) => {
if(err){
res.send({err: err, id: 5});
}else{
res.send(final);
console.log(final);
}
})
}
})
}
})
}
})
}
}
})
});
Now in this code, if the initial block fails, the others don't execute but if the last ones fail, the initial block still gets passed, how can I improve the code so that if any query fails, the ithers fail too...
I've checked this but it didn't helped as I need a Node.js tutorial
How to stop all DB queries if one fails
this is my code
const mysqlssh = require('mysql-ssh');
var Promise = require('promise');
const startSSHSQLTunnel = () =>{
return mysqlssh.connect(
{
host: 'xxx.xxx.xx.xxx',
user: 'ball',
password: 'r252_bat'
},
{
host: '192.xxx.xxx.xxx',
user: 'portal',
password: 'r252_bat',
database: 'mydb'
}
)
}
exports.getSignupSummary = async() => {
let res = []
let queryStrings = ['SELECT year, WorkWeek, COUNT(*) AS Count from (SELECT YEAR(signed_up) as year, WEEK(signed_up) as WorkWeek from `chatbots` where signed_up is not null) temp_table group by WorkWeek, year',
'SELECT year, WorkMonth, COUNT(*) AS Count from (SELECT YEAR(signed_up) as year, MONTH(signed_up) as WorkMonth from `chatbots` where signed_up is not null) temp_table group by WorkMonth, year',
'SELECT COUNT(*) as count from `chatbots`']
//SELECT COUNT(*) as count from `chatbots`;
getUserData = function(qs, cb) {
startSSHSQLTunnel().then(client => {
client.query(qs,
function(err, results) {
if (err)
return cb(err);
cb(undefined, results);
})});
}
// Usage:
queryStrings.map(x => {
getUserData(x,
function(err, results) {
res.push(results);
}
)
});
console.log(res);
}
I am trying to get the query results and store in an array called "res"
however I am facing the following issues
the results from the callback function can be console.logged but if I store in array and then try to print it out, I see an empty array.
I tried to use async -> await but it was no use
I tried to encapsulate everything in a new promise and then resolve the results but that was no point as I got an empty promise
please advise
You should try something like this:
exports.getSignupSummary = async() => {
let queryStrings = ['SELECT year, WorkWeek, COUNT(*) AS Count from (SELECT YEAR(signed_up) as year, WEEK(signed_up) as WorkWeek from `chatbots` where signed_up is not null) temp_table group by WorkWeek, year',
'SELECT year, WorkMonth, COUNT(*) AS Count from (SELECT YEAR(signed_up) as year, MONTH(signed_up) as WorkMonth from `chatbots` where signed_up is not null) temp_table group by WorkMonth, year',
'SELECT COUNT(*) as count from `chatbots`']
//SELECT COUNT(*) as count from `chatbots`;
getUserData = function(qs, cb) {
startSSHSQLTunnel().then(client => {
client.query(qs, function(err, results) {
if (err) return cb(err);
cb(undefined, results);
});
});
}
// Usage:
const promises = queryStrings.map(x => {
return new Promise((resolve, reject) => {
getUserData(x, function(err, results) {
if (err) reject(err);
resolve(results);
});
});
});
const res = await Promise.all(promises);
console.log(res);
}
This code uses the .map function to create a promise for each of your queries and store it in an array.
Then we use await Promise.all to wait for all the promises to be resolved.
I'm using node with Mysql and here's my problem.
I'm trying to add new photos on my database and return it as an array
here is my function :
function addNewPhotos(_id, files) {
var deferred = Q.defer();
var new_photos = []
_.each(files, function (one) {
var data = [
one.path,
_id,
0
]
var sql = 'INSERT INTO photos(photo_link, id_user, isProfil) VALUES (?, ?, ?)';
db.connection.query(sql, data, function (err, result) {
if (err)
deferred.reject(err.name + ': ' + err.message);
var sql = 'SELECT id_user, photo_link, isProfil FROM `photos` WHERE id = ?';
if (result){
db.connection.query(sql, [result.insertId], function(err, photo) {
if (err) deferred.reject(err.name + ': ' + err.message);
if (photo) {
new_photos.push(photo[0]);
}
});
}
})
})
deferred.resolve(Array.prototype.slice.call(new_photos));
return deferred.promise}
The Insert works well but i can't retrieve the results to send them back to the client. (my array is empty)
Thanks.
Always promisify at the lowest level, in this case db.connection.query().
if(!db.connection.queryAsync) {
db.connection.queryAsync = function(sql, data) {
return Q.Promise(function(resolve, reject) { // or possibly Q.promise (with lower case p), depending on version
db.connection.query(sql, data, function(err, result) {
if(err) {
reject(err);
} else {
resolve(result);
}
});
});
};
}
Now the higher level code becomes very simple :
function addNewPhotos(_id, files) {
var sql_1 = 'INSERT INTO photos(photo_link, id_user, isProfil) VALUES (?, ?, ?)',
sql_2 = 'SELECT id_user, photo_link, isProfil FROM `photos` WHERE id = ?';
return Q.all(files.map(function(one) {
return db.connection.queryAsync(sql_1, [one.path, _id, 0]).then(function(result) {
return db.connection.queryAsync(sql_2, [result.insertId]);
});
}));
};
To prevent a single failure scuppering the whole thing, you might choose to catch individual errors and inject some kind of default ;
function addNewPhotos(_id, files) {
var sql_1 = 'INSERT INTO photos(photo_link, id_user, isProfil) VALUES (?, ?, ?)',
sql_2 = 'SELECT id_user, photo_link, isProfil FROM `photos` WHERE id = ?',
defaultPhoto = /* whatever you want as a default string/object in case of error */;
return Q.all(files.map(function(one) {
return db.connection.queryAsync(sql_1, [one.path, _id, 0]).then(function(result) {
return db.connection.queryAsync(sql_2, [result.insertId]);
}).catch(function() {
return defaultPhoto;
});
}));
};
Do the return in your async loop function when all has been done
function addNewPhotos(_id, files) {
var deferred = Q.defer();
var new_photos = [];
var todo = files.length;
var done = 0;
_.each(files, function (one) {
var data = [
one.path,
_id,
0
]
var sql = 'INSERT INTO photos(photo_link, id_user, isProfil) VALUES (?, ?, ?)';
db.connection.query(sql, data, function (err, result) {
if (err)
deferred.reject(err.name + ': ' + err.message);
var sql = 'SELECT id_user, photo_link, isProfil FROM `photos` WHERE id = ?';
if (result){
db.connection.query(sql, [result.insertId], function(err, photo) {
if (err) deferred.reject(err.name + ': ' + err.message);
if (photo) {
new_photos.push(photo[0]);
}
if(++done >= todo){
deferred.resolve(Array.prototype.slice.call(new_photos));
return deferred.promise
}
});
}
else
{
if(++done >= todo){
deferred.resolve(Array.prototype.slice.call(new_photos));
return deferred.promise;
}
}
})
})
}
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) {
}