NodeJS/Mysql - Reference results from SELECT * statement - mysql

I have a segment like the following:
sql.query("SELECT * FROM tasks WHERE groupId = ? AND completed = 0", res[0].groupId, (err, res) => {
if (err) {
console.log("Error selecting from TASKS: ", err);
return result(null, res);
}
console.log("tasks: ", res);
return result(null, res);
})
In this case, you can see how the results of a previous query ( res[0].groupId ) are being plugged into the statement shown here, and it works.
I want to add another query after this one which will use a similar structure, statement something like: "SELECT * FROM updates WHERE taskId = ?". In this case, I want to use ALL of the task IDs resulting from the previous statement to plug into this query. How do I do that? I envision something like res[*].taskId in my head - no idea if that works, but that should give you the idea.

Related

trying to get data from two requests

I try to get data from two requests on two table. But I've some difficulties to get back them as I expect. I've some group andfor each group I want to get the list of all element included in this group. So I want all groups id and all items related to them.
So I execute the second query into the callback of the first into a loop to execute the query as many time as I've results from the first query. I think thant my problem come from the loop
Groupe.getGroupeAndEqs = function getGroupeAndEqs(result) {
sql.query("SELECT DISTINCT idGrp FROM groupe_equipement", function (err, res){
if (err) {
console.log("error: ", err);
result(err, null);
}
else {
for (var i = 0; i < res.length; i++){
sql.query("SELECT e.nom FROM equipement as e, groupe_equipement as g where g.idGrp=? AND e.id = g.idEq", res[i].idGrp, function(err, res2){
if(err){
console.log("error: ", err);
result(err, null);
}
else{
// result(null, res);
//I try to create an attribute with the result of the second query
res[i].equipements += res2;
//console.log(res[i]);
//resu += result(null, res);
console.log(res2);
}
});
}
result(null, res);
}
});
}
I only get the result of the first query
You can do the whole thing in a single query. That may half your total process time. Check this query.
select g.idGrp, group_concat(distinct e.nom) from equipement e
inner join groupe_equipement g
on e.id = g.idEq
group by g.idGrp

nodejs throws error with mysql like query via prepared statements

Am retrieving values from database using nodejs.
I implemented mysql like query via prepared statement to ensure that sql injection attack is eliminated. my problem is that it does not retrieve any result. it just show empty results in the console please can someone point to me what is wrong with the query
exports.autosearch = function (req, res) {
//var search = req.body.searchText;
var search = 'bukatti';
//db.query('SELECT * FROM users WHERE name like ?', ['%' + search + '%'], function (error, results, fields) {
db.query('SELECT * FROM users WHERE name like ?', ['%search%'], function (error, results, fields) {
console.log(results);
});
}
Thanks
I have found out my problem. i added the error log and discover that the was type error somewhere. This fix it anyway
db.query("SELECT * FROM users WHERE name like ?", ['%' + search + '%'], function (error, results, fields) {
Thanks

nodejs mysql multiple where query's

I've been working with mysql in nodejs for a bit and I can't seem to figure out how to use the query with multiple where statements.
Like:
SELECT * FROM user_information WHERE a=a or b=b
Right now i have this as my code:
connection.query("SELECT * FROM user_information WHERE username=" + registerarray[1] + " OR email=" + registerarray[3],function(err, results){
if (err){console.error(err);}
});
Thank you and best regards
Me
results is rows of response from mysql.
Let's simplify parts:
const
q = "SELECT * FROM user_information WHERE username=? OR email=?", // You can use placeholders like ? marks
args = [registerarray[1], registerarray[3]]; // array of values that will be set to placeholders (will be escaped for security)
connection
.query(
q, // our query
args, // placeholder values
(err, records) => { // query response scope begins here
if (err) {
console.error(err);
}
console.log('THIS IS RESULT OF QUERY EXECUTION:');
console.log(records); // this is result, already fetched array
});

Return error response in nodejs

Evening stack! Tonight I decided to play around with some NodeJS and I'm having a little trouble understanding the appropriate way for me to handle errors in this situation.
I have a table that simply stores playerName and the name must be unique. So rather than just try to insert and get an error, I want to first make a select and if I get a result, return a 400 to the user and let them know the name already exists. If not, continue on as normal, insert the name, and return a 203.
What I've got clearly isn't working. I've attempted a try/catch and that didn't work. And I clearly can't return an error with the methods I'm using. So what's a good way to go about this?
router.post('/addPlayer' , function(req, res, next){
var playerName = req.body.name;
if(playerName === undefined || playerName.length === 0)
{
return res.status(400).send('No name provided');
}
var query = 'SELECT name FROM players WHERE name LIKE ?';
var inserts = [playerName];
query = connection.format(query , inserts);
connection.query(query, function(err, results){
if(err) return res.status(500).send('Error connecting to database.');
if(results.length !== 0) return res.status(400).send('This name has already been used.');
});
query = 'INSERT INTO players (name) VALUES(?)';
inserts = [playerName];
query = connection.format(query , inserts);
connection.query(query, function(err){
if(err) return res.status(500).send('Error connecting to database.');
});
res.status(201).send("Added player: " + playerName);
});
In this current version my obvious problem is Node crashes complaining about not being able to set the headers after they've already been sent. I know what I need to do. Which is end the execution of the route and return the error to the browser, but I'm just not clear on how to best go about that.
I'm using the Express framework and mysql.
Thanks.
The problem is you're running both queries in parallel. So the INSERT is executed before the response of the SELECT is received. Which means that there is a race condition. Both queries tries to send res.status() but one will happen after the other which causes the error.
To fix this, wait until the SELECT is received then do your INSERT:
var query = 'SELECT name FROM players WHERE name LIKE ?';
var inserts = [playerName];
query = connection.format(query , inserts);
connection.query(query, function(err, results){
if(err) return res.status(500).send('Error connecting to database.');
if(results.length !== 0) return res.status(400).send('This name has already been used.');
query = 'INSERT INTO players (name) VALUES(?)';
inserts = [playerName];
query = connection.format(query , inserts);
connection.query(query, function(err){
if(err) return res.status(500).send('Error connecting to database.');
res.status(201).send("Added player: " + playerName);
});
});
Is there anything wrong with sending the error(err) itself? For example:
if (err)
res.send(err);

Variable in MySQL Query causes error

I have a node.js app using node-mysql to query a MySQL database.
Problem: It appears that when I make the table name in the query a variable, things stop working. Did I miss out on something?
Working Node Code
client.query('SELECT * from tableA',
function(error, results, fields) {
if (error)
throw error;
callback(results);
});
Non-working Node Code
client.query('SELECT * from ?',
[ tableA ],
function(error, results, fields) {
if (error)
throw error;
callback(results);
});
You could probably just append the table name to the string (pseudo code, I don't know node.js)
client.query('SELECT * from ' + [tablaA],
function(error, results, fields) {
if (error)
throw error;
callback(results);
});
They reason why it's not working is pretty clear.
The query from the non-working code will be :
SELECT * from 'tableA'
A solution is the one from #Andreas, but you will have the same problem in a where statement or insert for other values you don't want to be escaped like "null" value. ( convert into a string)
Same problem here
Check out the source how format && escape from node-mysql works.