I'm sure this is a simple error in my syntax but I'm currently using a nodejs function to input into my SQL database, however, while the overall query works, and some variables get input correctly, a couple are input as undefined, which has thrown me for a loop. I'll input the query below and I presume I either added extra punctuation where not required or something.
con.query("INSERT INTO _rounds(roundnum, roundse, roundtk, winner) VALUES('"+ roundnumres +"', '"+ roundse +"', '"+ roundtk +"', '"+ roundwinner +"')", function (err, result) {
});
For more information, the roundnumres and the roundtk variables are the ones inserted as undefined, and are both defined by a random string generator which looks as follows:
function makese(length) {
var roundse = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var d = 0; d < length; d++ ) {
roundse += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return roundse;
}
var roundse = makese(20);
Any help would be appreciated!
you could do this. you don't have to concat strings using plus
const query = `INSERT INTO _rounds(roundnum, roundse, roundtk, winner) VALUES('${roundnumres}', '${roundse}, '${roundtk}', '${roundwinner}')"
con.query(query, () => {})
Related
I am trying to use an array of values to populate an escaped sql query. The array being accepted.
I was using:
function genUpdateString(settings) {
var sql = "";
var first = true;
for (attr in settings) {
if (
settings[attr] != undefined &&
attr != "userid" &&
attr != "api_key"
) {
if (first) {
first = false;
} else {
sql += ", ";
}
sql += attr + "='" + settings[attr] + "'";
}
}
return sql;
}
sql_update = genUpdateString(...);
var sql = "UPDATE user SET " + sql_update + " WHERE name = '" + newSettings.userid + "'";
myCon.query(sql, (err, result) => {
This works fine but when I tried to move to the escaped format it crashes:
var sql = "UPDATE user SET ? WHERE name = ?";
myCon.query(sql, [sql_update, userid], (err, result) => {
When I create the string manually it runs through fine and updates my database tables but using the second method it crashes with the error:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''age=\'33\'' WHERE name = 'Josephy Krakowski'' at line 1
Your genUpdateString function isn't SQL injection safe either – just adding single quotes isn't secure.
Something like this is – we're generating the query fragment with question marks and the args "in parallel".
function genUpdateAndArgs(map) {
const names = [];
const args = [];
for(var key in map) {
const value = map[key];
if(value !== undefined) {
names.push(key);
args.push(value);
}
}
// ['foo', 'bar'] => 'foo = ?, bar = ?'
const namesFragment = names.map((name) => `${name} = ?`).join(', ');
return [namesFragment, args];
}
const settings = {
'foo': 123,
'bar': 456,
};
const userId = 1337;
const [namesFragment, updateArgs] = genUpdateAndArgs(settings);
const query = `UPDATE user SET ${namesFragment} WHERE name = ?`;
const args = [].concat(updateArgs).concat(userId);
console.log(query, args);
The output is
UPDATE user SET foo = ?, bar = ? WHERE name = ?
[ 123, 456, 1337 ]
which you could then plug into db.query...
However I really heartily recommend a query builder like Knex instead – in Knex, the same would be approximately
knex('user')
.where('name', userId)
.update(settings)
I'm coding opensource project in the university course
It is a function to search the value of another table by dividing input keyword by comma.
under this example data
Python,CPP,Csharp
var keyword = result[0].keyword;
var keyword_arr = [];
var keyword_split = keyword.split(',');
for (var i in keyword_split)
{
keyword_arr.push(keyword_split[i]);
}
I have succeeded in separating them with commas like above, but I'm looking for a loop in sequelize.
"Error: Can not set headers after they are sent."
An error is returned and is not executed.
I want to output the results merged. What should I do?
my code is
for (i = 0; i < keyword_arr.length; i++) {
query += models.contents.findAll({
where: {keyword: {like: '%' + keyword_arr[i] + '%'}},
raw: true
});
}
Regards.
You were in the right direction , but here it his how you can do :
queries = [];
for (i = 0; i < keyword_arr.length; i++) {
queries.push({keyword: {like: '%' + keyword_arr[i] + '%'}});
}
models.contents.findAll({
where: {
$or : queries
}
raw: true
}).then(results => {
console.log(results); // <---- Check this
})
NOTES :
models.contents.findAll() //<---- Returns promises
You can't just combine the promises by += as its not string or number
like that
In your case , it will create and run the query for each tag , so
that's not proper way of doing , you should combine the tags and create a single query as I did
I am using express and npm mysql (Link)
I want to do a call using
query('SELECT * FROM TABLE WHERE ?', where, cb)
where is a javascript object f.e. : {col1: 'one', col2: 'two'}
But it seems that this doesn't work. It works for SET though to update multiple columns at once.
I want a general method where I can send a different combination of columns to search. I was wondering if there is a built in method to do this.
Meanwhile, I created this script:
var andQuery = "";
var andParams = [];
var isFirst = true;
for (var filter in where) {
if (where.hasOwnProperty(filter)) {
if(!isFirst) {
andQuery += " AND ? ";
} else {
andQuery += " ? ";
isFirst = false;
}
andParams.push({[filter]: where[filter]});
}
}
db.query(
'SELECT * FROM `Table` WHERE ' + andQuery, andParams, (err, results) => {
I'm trying to figure out the correct way of passing custom data to a query call to be made available in the callback.
I'm using MySQL library in nodejs (all latest versions).
I have a call to connection.query(sql, function(err, result) {...});
I couldn't find a way to 1) pass custom data/parameter to the call so that 2) it can be made available when the callback is invoked.
So what is the proper way of doing so?
I have the following (pseudo-code):
...
for (ix in SomeJSONArray) {
sql = "SELECT (1) FROM someTable WHERE someColumn = " + SomeJSONArray[ix].id;
connection.query(sql, function (err, result) {
...
var y = SomeJSONArray[ix].id;
};
}
From the code above, I need to be able to pass the current value of "ix" used in the query to the callback itself.
How do I do that?
If you are using node-mysql, do it like the docs say:
connection.query(
'SELECT * FROM table WHERE id=? LIMIT ?, 5',[ user_id, start ],
function (err, results) {
}
);
The docs also have code for proper escaping of strings, but using the array in the query call automatically does the escaping for you.
https://github.com/felixge/node-mysql
To answer the initial question with a complete answer/example to illustrate, wrap the callback with an anonymous function which immediately creates a scope containing a "snapshot" if you will of the data passed in.
var ix=1;
connection.query('SELECT 1',
(function(ix){
return function(err, rows, fields) {
console.log("ix="+ix);
console.log(rows);
};
})(ix));
For those new to this concept as I was 20 minutes ago, the last })(ix)); is the outer var ix=1 value which is passed into (function(ix){. This could be renamed (function(abc){ if you changed the console.log("ix="+abc);
fwiw (Thanks Chris for the link which filled in the blanks to arrive at a solution)
While it is OK to pass variables or objects to a mysql query callback function using the tactic described earlier -- wrapping the callback function in an anonymous function -- I think it is largely unnecessary, and I'll explain why with an example:
// This actually works as expected!
function run_query (sql, y) {
var y1 = 1;
connection.query (sql, function (error, rows, fields) {
if (! error)
{
var r = rows[0];
console.log ("r = " + r[1]);
console.log ("x = " + x);
console.log ("y = " + y);
console.log ("y1= " + y);
console.log ("");
}
else
{
console.log ("error = " + error);
}
});
};
var x = 5;
console.log ("step 1: x = " + x);
run_query ("SELECT 1", x);
x = x + 1;
console.log ("step 2: x = " + x);
run_query ("SELECT 1", x);
x = x + 1;
console.log ("step 3: x = " + x);
Produces the following output:
step 1: x = 5
step 2: x = 6
step 3: x = 7
r = 1
x = 7
y = 5
y1= 5
r = 1
x = 7
y = 6
y1= 6
The fear is that the second call to run_query() will overwrite the variable y and/or y1 before the first call to run_query() has a chance to invoke its callback function. However, the variables in each instance of the called run_query() function are actually isolated from each other, saving the day.
MySQL con.query has overloaded function. Inside of callback you use global variable or any variable that is passed into your function parameter. For example:
Example 1: it takes sql string and callback function
var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers;
con.query(sql, function (err, result) {
if (err) throw err;
console.log(adr);
});
Example 2: it takes sql string, parameter and callback function
var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE address = ?';
con.query(sql, [adr], function (err, result) {
if (err) throw err;
console.log(adr);
});
I have an issue with extracting value from object. I want to check if my SQL table have the asked row:
var checkRow = function(connection,chekedColumn,chekParam, checkVal){
connection.query('SELECT EXISTS(SELECT '+ chekedColumn +' FROM asterisk.users where ' +chekParam+'='+checkVal+')', function (err, rows) {
if(err) console.log('SQL suerry error')
else {
console.log(rows[0]); // output: { 'EXISTS(SELECT id FROM asterisk.users where name=1600)': 1 }
return (rows[0]);
};
});
};
but returned value from query is an object, and return(rows[0]) give just [object object] output. How can I extract value of this object?
You can use
Object.keys(obj)
to get the values of the object. See api reference for more info.
EDIT:
Just to elaborate abit more on this... how you'd go about getting it out is this.
// get the keys of the source
var keys = Object.keys( source );
// loop through the keys
for ( var i = 0; i < keys.length; i++ ) {
var key = keys[i];
var value = source[key];
//do something with value
}
The output is an object which you don't know. So try either:
console.log("Result: %j", rows[0]);
console.log(JSON.stringify(rows[0]));
console.log(require('util').inspect(rows[0], false, null));
to view the structure. After you know the keys, use it to access the data.
Thanks all for helps and for your ideas. Dmitry Matveev help me to understand how to identify object properties(Objekt.keys()). And thanks to user568109 for reminding of asynchronous function, so I use callback. Final code:
var checkRow = function(connection,chekedColumn,chekParam, checkVal,callback){
connection.query('SELECT EXISTS(SELECT '+ chekedColumn +' FROM asterisk.users where ' +chekParam+'='+checkVal+')', function (err, rows) {
if(err) console.log('SQL suerry error')
else {
var keys=Object.keys(rows[0]);
keys.forEach(function(key) {
callback(rows[0][key]);
});
};
});
};
And for using this functions we need to call it like:
checkRow(connection,'id','name',name,function(value){
console.log(value)
})