Inserting multiple values in mysql using nodejs is causing parsing errors - javascript

I need to insert a record into mysql using nodejs. I am able to insert directly by typing values into the query just fine. I can insert using query + value syntax to concatenate the values but read this leaves open the risk of SQL injection.
let sql ="INSERT INTO gametypes (strGameType, intTeamSize, intMaxPlayers, intMinPlayers) Values ? ";
var gametype ="Solo Zonewars";
var teamSize =1;
var maxPlayers = 16;
var minPlayers = 10;
var values = [gametype, teamSize, maxPlayers, minPlayers];
console.log("connected as id '" + connection.threadId);
connection.query(sql, values, function(err, result, fields) {
connection.release();
if(!err) {
console.log(result);
}else console.log(err);
});
Below is the attached error I am getting from mysql. It seems like it is putting extra quotes around the gametype variable and not attempting to insert the rest into the query. Any ideas?
error from mysql

I would suggest you to not use an array and replace your query by this one
let sql ="INSERT INTO gametypes (strGameType, intTeamSize, intMaxPlayers, intMinPlayers) Values (?, ?, ?, ?) ";
then you will pass the values one by one

If you are having 4 value parameters to the query, you should have 4 question marks as well. Try with the first line changed to:
let sql ="INSERT INTO gametypes (strGameType, intTeamSize, intMaxPlayers, intMinPlayers) Values (?, ?, ?, ?) ";

You can try wrapping your values into an array, as this method is intended for inserting multiple rows:
let sql ="INSERT INTO gametypes (strGameType, intTeamSize, intMaxPlayers, intMinPlayers) Values ? ";
var gametype ="Solo Zonewars";
var teamSize =1;
var maxPlayers = 16;
var minPlayers = 10;
var values = [
[gametype, teamSize, maxPlayers, minPlayers]
];
console.log("connected as id '" + connection.threadId);
connection.query(sql, [values], function(err, result, fields) {
connection.release();
if(!err) {
console.log(result);
}else console.log(err);
});

Related

How can i use/send the information inside an array from one block to another block js

So my issue is this I have a SQL query that push its result into an array
connection.query('SELECT id FROM parada WHERE ubi_calle_id =? ',[calleID], async (err,resultid)=>{
for (i =0; i < resultid.length; i++){
ParIds[ParIds.length] = {
id: resultid[i].id
}
}
for(i=0; i < ParIds.length; i++){
parID = ParIds[i].id
//console.log(parID, "par id")
connection.query(`SELECT parada.id , trayecto.recorrido_id, recorrido.linea_id, lineas.name AS nombre_linea, lineas.ramal FROM (((parada INNER JOIN trayecto ON parada.id= trayecto.parada_id) INNER JOIN recorrido ON trayecto.recorrido_id = recorrido.id)INNER JOIN lineas ON recorrido.linea_id= lineas.id) WHERE parada.id = ${parID} `, async (err,resultLineas)=>{
if (err) throw err;
//console.table(resultLineas)
lineas.push(resultLineas);
console.log(lineas, "esto")
});
}
})
So each element of the array lineas is an array of the result of the second query and it show something like this lineas = [[1,2,3],[1,4],[3]]
But now I have another SQL query that brigs me another result
connection.query('SELECT parada.*, calle.name AS ubi1, c.name as ubi2 FROM ((parada INNER JOIN calle ON parada.ubi_calle_id = calle.id)INNER JOIN calle c ON parada.ubi_casi = c.id) WHERE ubi_calle_id =? ',[calleID], async (err,result)=>{ });
Inside of this second SQL query "block" I need to use or somehow bring the array "lineas" that I got from the first SQL query but I can't do it, If I try to use it inside the second SQL query the array is always empty "console.log (lineas) will show []. So how can I save that array from the first SQL query in way where console.log(lineas) inside the second SQL query will also bring me lineas= [[1,2,3],[1,4],[3]]
PS : I'm so sorry for my bad english I tried my best.
PS2 : The only way I can somehow use the data from lineas inside the second SQL query is if I put the second SQL query inside the first 1 which is not an option since it will be inside the for loop.

"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();', ..)

sqlite - unable to query web db with WHERE clause

I'm using the WHERE clause while trying to query my sqlite database. I know there is data in the db which I should be able to retrieve based on the conditionals in my query, but I can't seem to get it to work.
When I query without conditionals...
sql = 'select LocationGUID, ID, Fullname FROM tblUser';
I'm able to return all the data from the selected columns. Is this is a quotation issue? I've tried single and double-quotes around the conditional values but the number of rows I return is still 0.
Javascript:
sql = 'select LocationGUID, ID, Fullname FROM tblUser WHERE UserName=\'mike\' AND Password=\'mike123\'';
mydb = getDBConn();
mydb.transaction(function(tx) {tx.executeSql(sql, [], function(tx,results) {
var size = results.rows.length;
console.log(size);
for (var i=0;i<size;i++) {
for (var key in results.rows.item(0)){
var row = results.rows.item(i);
console.log(row[key]);
}
}
SQLite DB
The correct query to find this row would be this:
SELECT ... FROM tblUser WHERE UserName = 'mike ' AND ...
You might want to change the code that stores the data to remove these unwanted spaces.
To fix the database, use something like this:
UPDATE tblUser SET UserName = rtrim(UserName)

how to get last inserted row id in sqlite

function insertToProject(cast, pName)
{
db.execute('INSERT INTO project (cd, pn) VALUES (?,?)', cast, pName);
var x = last_insert_rowid();
return x;
}
I have been trying this using javascript in titanium appcelerator. Can anybody tell me what I am doing wrong?
For this you can use the lastInsertRowId property of database object.
You can use like:
var x = db.lastInsertRowId;
lastInsertRowId
lastInsertRowId : Number
The identifier of the last populated row
Please check this link for more details : Titanium.Database.DB
You may also do:
db.transaction(function(tx) {
tx.executeSql("INSERT INTO project (cd, pn) VALUES (?,?)", cast,
function(tx, res) {
var id = res.insertId;
});
});
Thus, getting the result of the successful insert and then its property insertId

Categories