How to save information from an SQL query to a variable - javascript

I'm trying to save the information I get from my inmatefirst column with my SQL query into the variable "first'. I was wondering what the correct syntax/approach was to doing this.
let sql = `SELECT * FROM inmates WHERE inmatefirst = ? AND inmatelast = ? AND dob = ?`;
let query = db.query(sql, [search.first, search.last, search.dob], (err, result) => {
if (err) throw err;
if (result.length != 0) {
res.render(path.resolve('./myviews/modify'), {
good: 'Person Found - Please Enter Updated Information',
first: result.inmatefirst,
last: result.last,
dob: result.dob,
sex: result.sex
});
});
});

Your SQL says, in part, this:
SELECT * FROM inmates WHERE inma...
You've asked for every column from the table. That can make life confusing.
Instead, spell out the columns you want. Your Javascript indicates that you want these ones:
SELECT inmatefirst, last, dob, sex FROM inmates WHERE inma...
(It's possible that is the wrong set of columns. Check it.
Then, as #barmar pointed out, use result[0].first etc, because result is an array of objects, one for each row of your resultset.

Related

"Order by" results from SQLITE query not ordered

I am working on a webshop-project. I am trying to get sorted results based on parameter values from a sqlite database. I am trying to sort products based on "select" values.
In my app.js
app.get('/sortMaleProducts', function(request, response){
var sortValues = request.query.sortValue;
if(sortValues == 'priceASC')
{
sortValues = ["man", "price", "ASC"];
}
else if(sortValues == 'priceDESC')
{
sortValues = ["man", "price", "DESC"];
}
db.sortMaleProducts(sortValues, function(error, clothes){
if(error){
console.log("Error: "+ error);
}
else{
console.log(clothes)
const model = {
clothes
}
response.render("man.hbs", model)
}
})
})
In my db.js
exports.sortMaleProducts = function(sortValues, callback){
const query = 'SELECT * FROM products WHERE gender = ? Order by ?, ?'
db.all(query, sortValues, function(error, clothes){
console.log(clothes);
callback(error, clothes);
})
If I hardcode the query like:
const query = 'SELECT * FROM products WHERE gender = 'man' Order by price ASC'
Then it works....But I want to use user inputs so I can reuse code..
If you want to sort by a column, that column name has to appear directly in the query. What you're doing sorts the results by the strings 'price' and 'ASC', which are the same for every row so any order of results is sorted.
You can't use column names as parameters anywhere else in a query either, like in the columns to return or in a WHERE. They have to be present when the statement is prepared by compiling it into sqlite's internal bytecode, which happens before any parameter binding or the execution of the query.

what the best way to insert a relationship table in mysql using NodeJS

First of all I have to say I'm totally newbi in NodeJS technologies.
But, I've tried to do something to try to learn it.
This is the problem:
I have 3 tables (PARTICIPANT, ADDRESS_PARTICIPANT and INSCRIPTION).
The ADDRESS_PARTICIPANT contains participant_id (it's the participant's address).
The INSCRIPTION contains participant_id
So, to store a inscription row, at first I need to save the PARTICIPANT and the ADDRESS_PARTICIPANT. Only after this I could insert INSCRIPTION
I'm doing this in the way i've learn, but I think there are a lot of nested ifs.
How could I improve this code? Someone told me with Promise i'll well.. but I don't know. Someone could help me? Thanks
Here is the code:
this.save = function(data, retur) {
var con = db();
const SQL_INSERT_PARTICIPANT =
`INSERT INTO participant (nome_completo, tipo_funcionario, data_nascimento, sexo, unidade, cpf, email, telefone, telefone_emergencia) VALUES( ? )` ;
const SQL_INSERT_ADDRESS_PARTICIPANT =
`INSERT INTO endereco_participante (participant_id, cep, estado, cidade, bairro, endereco, numero) values( ? )`;
const SQL_INSERT_INSCRIPTIONS = `......`
var values = [
data.nome_completo, data.tipo_funcionario, new Date(dateToEN(data.data_nascimento)), data.sexo, data.unidade, data.cpf_funcionario, data.email, data.telefone, data.telefone_emergencia
]
const insertParticipante = con.query(SQL_INSERT_PARTICIPANT , [values], function (err, result) {
if (err) throw err;
var values_end = [
result.insertId, data.cep, data.estado, data.cidade, data.bairro, data.endereco, data.numero
]
if (result.affectedRows > 0 ) {
const insertEndPart = con.query(SQL_INSERT_ADDRESS_PARTICIPANT , [values_end], function(err, result2 ) {
if (err) throw err;
console.log('Number of records inserted in ADDRESS_PARTICIPANT table: ' + result2.affectedRows);
console.log('insertId.: ' + result2.insertId)
if (result.affectedRows > 0 ) {
const insertInscricao = con.query(SQL_INSERT_INSCRIPTIONS, [values_ins], function(err, result3) {
console.log(`Inscription recorded! id: `+resul3.insertId)
})
}
})
}
})
}
You can use MySQL's LAST_INSERT_ID i assume every table has a primray key column with a auto_increment option.
With no argument, LAST_INSERT_ID() returns a BIGINT UNSIGNED (64-bit)
value representing the first automatically generated value
successfully inserted for an AUTO_INCREMENT column as a result of the
most recently executed INSERT statement. The value of LAST_INSERT_ID()
remains unchanged if no rows are successfully inserted.
https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_last-insert-id
Then you can use these INSERT's in NodeJS instead.
INSERT INTO participant (nome_completo, tipo_funcionario, data_nascimento, sexo, unidade, cpf, email, telefone, telefone_emergencia) VALUES( <other columns> )
This insert below will use LAST_INSERT_ID() to get the participant.id
INSERT INTO endereco_participante (participant_id, cep, estado, cidade, bairro, endereco, numero) values( LAST_INSERT_ID(), <other columns> )
With three table the problem gets more complex.
Then you can use MySQL's user variables.
INSERT INTO participant (nome_completo, tipo_funcionario, data_nascimento, sexo, unidade, cpf, email, telefone, telefone_emergencia) VALUES( <other columns> )
SET #participant_id = LAST_INSERT_ID();
INSERT INTO endereco_participante (participant_id, cep, estado, cidade, bairro, endereco, numero) values( #participant_id, <other columns> )
SET #endereco_participante_id = LAST_INSERT_ID();
Then you can use #participant_id and #endereco_participante_id in the third insert query. (which seams you didn't provided in your question).
Note the SET queries are separated queries so you need to execute them also with con.query('SET #participant_id = LAST_INSERT_ID();', ..)

Check if MySQL row exists - Node.JS

Previous post I will refer to later
I am making a Discord bot which uses MySQL, but that shouldn't matter, I am trying to do a blacklist database so users in it can't use my bot
This is what I got so far:
con.query("SELECT EXISTS( SELECT 1 FROM `blacklist` WHERE `id` = '"+message.author.id+"')", function(error, result, field) {
if(error) throw error;
});
And this kinda works, this is my output
[ RowDataPacket {
'EXISTS( SELECT 1 FROM `blacklist` WHERE `id` = \'227090776172134400\')': 1 } ]
And the last digit works like a boolean, 1 if the row exists, 0 if it does not
But my problem is, that I can't seem to figure out how to check if it's a zero or not because it's an object
Why can't you make the query string a variable that you can later query on. For example:
let conStr = "SELECT EXISTS( SELECT 1 FROM `blacklist` WHERE `id` = '"+message.author.id+"')";
con.query(conStr, function(error, result, field) {
if(error) throw error;
console.log(result[conStr]); //--> 1
});

Query check where

I'm trying to check in a NodeJS query where a user his id is e.g. 1 and his private_number is 25, the following code doesn't work.
query('SELECT * FROM `users` WHERE `user` = '+pool.escape(user)+', `private_number` ='+pool.escape(number), function(err, row) { //get if the player has a query with the same code
});
Is this even properly possible?
you can use template strings
query(`SELECT * FROM users WHERE user = ${pool.escape(user)} AND
private_number = ${pool.escape(number)}`), function(err, row) {
})
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
P.S. when you have multiple conditions in WHERE clause you need to 'connect' them with logical operator like AND or OR

Mongojs fetching data from two collections and merging the result

I am a mongodb newbie and would greatly appreciate help on this problem described below.
I have two collections "users" and "bags". The user collections scheme has {username, firstname, lastname} and the bag collection schema has {username, bagname, bagimage}.
While fetching users bags, I also want to display the firstname and lastname. My problem is that I cant seem to be able to frame a query correctly. I am using nodejs and mongojs driver. Below is my query for fetching all bags
thmConfig.db.bags.find({status: "1"}).sort({$natural:-1}, function(err, data)
{
var bagList = '{"bags":[';
if( err || !data) res.send('[{"status": "0"}]');
else data.forEach( function(innerData) {
console.log(innerData.username);
bagList += JSON.stringify(innerData)+",";
/*
This is where I would lke to also append the firstname from the
users collection
*/
});
console.log(bagList.slice(0,1));
res.write(magList.slice(0,-1));
res.end(']}');
});
I would greatly appreciate any help or pointers about this. I dont have a choice about changing the driver, so I specifically want to implement this using mongojs for now.
Thanks and regards,
Titash
I don't think that you have much choice other than reading from the users collection and doing this "join" operation programmatically.
You can either read the user document per each bag (inside your loop), or read the entire users collection into an object in advance, and do lookups by username
You could use the $in operator for that.
Pseudo-code(ish):
// get an array of bags matching your query
db.bags.find({status: "1"}).sort({$natural:-1}, function(err, bags) {
// get a list of usernames from the bags:
var usernames = bags.map(function(bag) { return bag.username; });
// perform query on user table: find all users for which we have a bag
db.users.find({ username : { $in : usernames } }, function(err, users) {
// create a mapping of username -> first name for easy lookup
var usernames = {};
users.forEach(function(user) {
usernames[user.username] = user.firstname;
});
// map first names to bags
bags.forEach(function(bag) {
bag.firstname = usernames[bag.username];
});
// done: return it as JSON (no need to build a JSON string ourselves)
res.send({ bags : bags });
});
});

Categories