I want to make the ORDER BY dynamic in mysql query in node.js. But it's not working. I console.log the multiQuery variable and everything looks perfect but when ran it simply doesn't work. This is what I have:
var order,
multiQuery;
if(req.query.o){
order = req.query.o;
}else{
order = "views";
}
multiQuery = 'SELECT COUNT(Category) AS Count FROM posts;';
//PROBLEM LIES HERE IN THE SECOND ONE
multiQuery += 'SELECT ID, Title, Img_path, Category, Views FROM posts WHERE Category = ' + connection.escape(category) + ' ORDER BY' + connection.escape(order) + 'DESC LIMIT ' + start_from + ', 15;';
connection.query(multiQuery, function(err, result){
});
This does not work:
SELECT foo FROM bar ORDER BY 'baz';
This does work :
SELECT foo FROM bar ORDER BY baz;
Did you try removing the quotes that connection.escape adds?
Try using this:
function escapeSansQuotes(connection, criterion) {
return connection.escape(criterion).match(/^'(\w+)'$/)[1];
}
then use escapeSansQuotes(connection, order) instead of connection.escape(order).
try using a proper spacing for each token
//PROBLEM LIES HERE IN THE SECOND ONE
multiQuery += 'SELECT ID, Title, Img_path, Category, Views
FROM posts WHERE Category = ' + connection.escape(category) +
' ORDER BY ' + connection.escape(order) +
' DESC LIMIT ' + start_from + ', 15;';
Check if you did enabled the multi-query into your connection object.
http://nickolayconsulting.com/node-js-and-multiple-sql-calls-in-one-query/
Support for multiple statements are disabled by default for security
reasons (it allows for SQL injection attacks if values are not
properly escaped). To use this feature you have to enable it for your
connection:
var connection = mysql.createConnection({multipleStatements: true});
Related
I have a problem order by column name(String) when i have more than one word, like " Kafka Streams" and "Kafka Connectors". The order should be "Kafka Connectors", "Kafka Streams" but it order "Kafka Streams" ,"Kafka Connectors". The first word is ok, but second not. How can i resolve this?
I tried use substring and charindex, but the last one dont work in sequelize RAW queries.
sequelize.query(
'SELECT `technology`.`business_unit_id`, `technology`.`unit_reference_data_technology_id`' +
'FROM `unit_reference_data_technology` AS `technology`' +
'WHERE (`technology`.`description` LIKE (:name) ') ' +
'ORDER BY `technology`.`description` ASC, LIMIT ' + limit + ' OFFSET ' + offset + '', { model: Models.unit_reference_data_technology, mapToModel: true, replacements: { business_unit_id, name: '%' + text + '%', limit: 10,}, type: sequelize.QueryTypes.SELECT })
Example
I m using MySQL and a Sequelize (nodeJS).
Can anyone help me? My solution is ORDER BY first word ASC, second word ASC ( If the string have always 2 words)
I'm using node js to develope my project, i use mysql to store my data.
I have a problem when i select with like query, and it give an error like this:
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 'test'%' ORDER BY create_time DESC LIMIT 0,10' at line 1
SELECT * FROM user WHERE fullname LIKE N'%'test'%' ORDER BY create_time DESC LIMIT 0,10
I know error here is 'test' in query, but it's a string, i can't remove it, my code here:
data = {};
data.fullname = 'test';
data.start = 0;
data.limit = 10;
let getFullname = function (data, callback) {
return db.query("SELECT * FROM user WHERE fullname LIKE N'%?%' ORDER BY create_time DESC LIMIT ?,? ", [data.fullname,data.start,data.limit], callback);
}
How can i solve my problem, thank you!
You are right, problem is mysql package add single quote ', you can use following manner
return db.query(`SELECT * FROM user WHERE fullname LIKE N'%${data.fullname}%' ORDER BY create_time DESC LIMIT ?, ? `, [data.start,data.limit], callback);
or
data.fullname = '%' + data.fullname + '%';
return db.query("SELECT * FROM user WHERE fullname LIKE N? ORDER BY create_time DESC LIMIT ?,? ", [data.fullname,data.start,data.limit], callback);
CONCAT("%", ? , "%")
:)
this is part of my code :
##########
where += ` AND ( titre LIKE CONCAT("%", ? , "%") OR resume LIKE CONCAT("%", ? , "%") ) ` ;
vals.push(dataRes.rech) ;
vals.push(dataRes.rech) ;
#############
sql = `SELECT ######### WHERE 1=1 ${where}` ;
connection.query( sql , vals , async function(err, services, fields) {
if(err) rej({er : 1 , code : err , sql: sql , vals : vals}) ;
else{ res({er : 0 , data : services }) }
I'm currently trying to get the current date and try to save on my database but the only thing i get on my date column is 1982 , really strange ? Here is my code for the date and the mysql insertion :
DATE :
var dateTime = require('node-datetime')
var dt = dateTime.create();
var formatted = dt.format('Y-m-d');
console.log(formatted);
Mysql insertion :
pool.query(
'INSERT INTO jbets SET user = ' + pool.escape(tradingRequests[offer.id]['user']) +
', assetids = ' + pool.escape(assetidsSS) +
', value = ' + pool.escape(totalPrice) +
', minTicket = ' + pool.escape(minTicket) +
', maxTicket = ' + pool.escape(maxTicket) +
', total = ' + pool.escape(totalSkins) +
', jid = ' + pool.escape(jackpotRound) +
', token = ' + pool.escape(offer.id) +
',date =' + formatted
)
You should really be using placeholders.
You shouldn't be trying to convert the date object to that string format before inserting into a date field in the DB. The proper format would be YYYY-mm-dd HH:ii:ss, however you could let your MySQL library handle the conversion for you.
I suggest reading the Escaping Query Values section of the MySQL JS library documentation.
Try something like this:
pool.query('INSERT INTO jbets SET user = ?, assetids = ?, value = ?, ' +
'minTicket = ?, maxTicket = ?, total = ?, jid = ?, token = ?, date = ?',
[tradingRequests[offer.id]['user'], assetidsSS, totalPrice,
minTicket, maxTicket, totalSkins, jackpotRound, offer.id, dt]);
Use this code :
pool.query('INSERT INTO jbets (user, assetids, value, minTicket, maxTicket, total, jid, token, date) VALUES(pool.escape(tradingRequests[offer.id]['user']), pool.escape(assetidsSS), pool.escape(totalPrice), pool.escape(minTicket), pool.escape(maxTicket), pool.escape(totalSkins), pool.escape(jackpotRound), pool.escape(offer.id), NOW()));
Thanks for responding the problem was from my db i was need to change the ty to varchar
Currently, I am using string manipulation for passing value for multiple where clause.
Since docs for raw queries with replacements does not support multiple where clause and i cannot use simply use a find()
Since my requirement needs complex mysql queries which is not possible using find().
Is there any way of accomplish this basic task for multiple filtration in "Raw queries mode" ?
if(selector==""){
selector="where "+searchkey+" LIKE "+"'%"+searchvalue+"%'";
}
else
{
selector=selector+" and "+searchkey+' LIKE %' + searchvalue + '%';
}
sequelize.query('select ROLEID as RoleID,Rolename, CASE WHEN isactive = 1 THEN \'True\' ELSE \'False\' END as isactive , ' +
'GROUP_CONCAT(DISTINCT modID) ModID,' +
'GROUP_CONCAT(DISTINCT Modulename) Modulename,' +
'GROUP_CONCAT(DISTINCT Accestype) Accestype ' +
'from ' +
'( ' +
'select isactive,rl.roleid AS ROLEID,n.modnameID as modID, n.Mname as Modulename,rl.rolename as Rolename, r.Accestype as Accestype from mrole r ' +
'left join modname n ' +
'on r.modulename=n.modnameID ' +
'left join role rl ' +
'on rl.roleid=r.rolename '+
') as a '+selector+' GROUP BY ROLEID,Rolename,isactive '+
'limit :NUMBER_OF_ITEMS ' +
'offset :PAGE_NUMBER ', {
replacements: {
NUMBER_OF_ITEMS: parseInt(NUMBER_OF_ITEMS),
PAGE_NUMBER: parseInt(PAGE_NUMBER)
},
type: sequelize.QueryTypes.SELECT
}
).then(function(projects) {
var red = new Object();
red.rows = projects;
res.json(red);
})
Question 1:
I have the below MySQL query which works fine but I've just discovered this is not a safe approach as its open to SQL injection. As you can see the where clause is an issue if I wanted to pass as an argument.
_, err := dbmap.Select(&response.AppsData, "SELECT...", ?)
Any advice much appriciated.
where := ""
for i := 0; i < (len(acl_user_apps)); i++ {
fmt.Println(acl_user_apps[i].AppId)
fmt.Println(acl_user_apps[i].Permissions)
if where == "" {
where = "WHERE Apps.id=" + strconv.Itoa(acl_user_apps[i].AppId)
} else {
where = where + " OR Apps.id=" + strconv.Itoa(acl_user_apps[i].AppId)
}
}
query := "SELECT Apps.*, GROUP_CONCAT(DISTINCT IFNULL(AppCategoryMatches.category_id,'-1') SEPARATOR ',') as temp, GROUP_CONCAT(DISTINCT IFNULL(AppCategories.category_name,'-1') SEPARATOR ',') as tmp_name FROM Apps LEFT JOIN AppCategoryMatches ON AppCategoryMatches.app_id=Apps.id LEFT JOIN AppCategories ON (AppCategoryMatches.`category_id` = AppCategories.id) " + where + " GROUP BY Apps.id ORDER BY " + sort_by + " " + order_by + " LIMIT " + limit + " OFFSET " + offset)
_, err := dbmap.Select(&response.AppsData,query)
Question 2: Also just wondering if anyone has ever had issues passing ORDER argument...
_, err := dbmap.Select(&response.AppsData,
"SELECT Apps.*, GROUP_CONCAT(DISTINCT IFNULL(AppCategoryMatches.category_id,'-1') SEPARATOR ',') as temp, GROUP_CONCAT(DISTINCT IFNULL(AppCategories.category_name,'-1') SEPARATOR ',') as tmp_name FROM Apps LEFT JOIN AppCategoryMatches ON AppCategoryMatches.app_id=Apps.id LEFT JOIN AppCategories ON (AppCategoryMatches.category_id = AppCategories.id) GROUP BY Apps.id ORDER BY ?", "title")
This ORDER is the simplest thing ever... why isnt it working?
You absolutely don't want to be "escaping" any strings on your own, nor concatenating strings to make queries.
Go's database/sql (http://golang.org/pkg/database/sql/) package supports parameterised queries by default - e.g. db.Query("SELECT * FROM users WHERE id=? AND active=?", id, userStatus) - where ? acts as a placeholder for mySQL to handle your variables.
You can (in combination with parameterised queries) use a query builder like mgutz/dat that can help if you're not great at writing raw SQL. A package like that or sqlx also helps pack/unpack queries to/from structs or maps in your application.
There's also a great guide in this tutorial for using Go's database package. I highly suggest reading it.
I don't know Go language. But most of languages have function for escaping strings (PHP example: http://php.net/manual/en/function.mysql-real-escape-string.php). If you're inserting only integers to your query, you only need to convert values from string to int.
Check this out: http://astaxie.gitbooks.io/build-web-application-with-golang/content/en/09.4.html maybe you'll find some answers.
And about your ORDER - can you put here complete sql query that you're calling?