How do escape a MySQL LIKE statement in node-mysql?
Something along the lines of
"SELECT * FROM card WHERE name LIKE '%" + connection.escape(req.body.search) + "%'"
Results in
'SELECT * FROM card WHERE name LIKE \'%\'hello\'%\''
Which is a syntax error. If I use the alternative syntax of
connection.query("SELECT * FROM card WHERE name LIKE '%?%'", req.body.search, function () {});
Results in a similar syntax error. I've also tried
connection.query("SELECT * FROM card WHERE name LIKE ?", '%' + req.body.search + '%', function () {});
Which just ends up escaping the '%' sign.
Not sure why it's escaping the % in your last example, because that works fine for me:
// lifted from my code:
var value = 'ee20e966289cd7';
connection.query('SELECT * from django_session where session_key like ?', '%' + value + '%', ...)
// Result:
[ { session_key: '713ee20e966289cd71b936084a1e613e', ... } ]
When I turn on debugging in the driver (pass debug:true as argument to mysql.createConnection), it doesn't escape the percent sign:
{ command: 3,
sql: 'SELECT * from django_session where session_key like \'%ee20e966289cd7%\'' }
(it does escape the single quote, but that's for display purposes only)
(using mysql#2.0.0-alpha8)
i've had success with something like
"SELECT * FROM card WHERE name LIKE " + connection.escape('%'+req.body.search+'%')
How about
mysql.format("SELECT * FROM card WHERE name LIKE CONCAT('%', ?, '%')", req.body.search)
?
you can always do
variable = '%${variable}%'
"SELECT * FROM 'table' WHERE ('foo' LIKE ?);",
[variable], callback =>
I had the same problem and solved it like this:
function search(searchTerm) {
let replacement = `'%${searchTerm}%'`;
let sqlStatement = `SELECT * from clients where firstName LIKE ${replacement}`;
const [rows, fields, error] = connection.query(sqlStatement);
return rows;
}
Simple and easy way:
`SELECT * FROM card WHERE name LIKE ` + connection.escape(`%${req.body.search}%`)
Related
I have sql string written with template string syntax:
const sql = `select * from tbl_name where smth=$1 name like '%$2%'`;
const data = await execute(sql, [something, someName]);
I have problems with binding second param - $2 because of single quote. How should I write it properly ?
Error: Error: Query failed: bind message supplies 2 parameters, but prepared statement "" requires 1
I think you're supposed to use wildcards this way:
const sql = `select * from tbl_name where smth=$1 name like $2`;
const data = await execute(sql, [something, `%${someName}%`]);
I am trying to basically ignore the case sensitivity for my db2 sql select * query, so that I can populate the products to my catalogue page. Ex. If I type in my search bar 'squeege', I want the item 'Squeege' to populate, even if there is a difference in Upper/lower case. What is the best way to do this, based on the code I have below?
var searchProduct = "select * from LISTOFPRODUCTS where ITEM LIKE '%" + searchValue + "%'"
Thanks in advance for the help :)
I think this could work:
var searchProduct = "select * from LISTOFPRODUCTS where UPPER(ITEM) LIKE UPPER('%" + searchValue + "%'")
Also the same with LOWER()
Note that the trick is parse both values to UPPER() or LOWER() to match them.
You can use the function LOWER().
For example:
var searchProduct = "select * from LISTOFPRODUCTS where LOWER(ITEM) LIKE '%" + searchValue + "%'"
You can also consider using REGEXP_LIKE which has a case-insensitive option i
sql query does not accept array as value when it is used in a placeholder, It only returns one result even though result is greater than 1. Not using a placeholder and withouting escaping it works perfectly returns the right amount of results.
//works
SELECT * FROM users WHERE userId IN (" + followerIds.join() + ");";
//does not work
SELECT * FROM users WHERE userId IN (?);";
con.query(queryFollowerstTable, [followeringIsd.join()],function(err,result)..
All I had to do was parse followerIds.join() to an int and It worked.
followerIdsParsed = followerIds.join().split(',').map(Number);
followingIdsParsed = followingIds.join().split(',').map(Number);
var queryFollowerstTable = "SELECT * FROM users WHERE userId IN (?); SELECT *
FROM users WHERE userId IN (?);";
con.query(queryFollowerstTable, [followerIdsParsed, followingIdsParsed],
function(err, result) {..
Change
con.query(queryFollowerstTable, [followeringIds.join()],function(err,result)
to
con.query(queryFollowerstTable, followeringIds.join(),function(err,result)
In your original example:
SELECT * FROM users WHERE userId IN (" + followerIds.join() + ");";
You are passing in a string not an array
I'm trying to send an SQL query with javascript using a variable sourced from an input. In this input, characters like ' and " along with others may be entered.
Here's what my script function looks like:
function insertJobDesc (r) {
rowid=r;
var qty = document.getElementById('Qty' + r).value;
var desc = document.getElementById('Desc' + r).value;
desc = desc.replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"""').replace(/'/g, '"'"');
sendAsync("editDatabase.php?sql=UPDATE+jobdesc+SET+qty="+qty+",+description='"+desc+"',+rowID="+rowid+"+WHERE+id="+rowid+"+AND+jobID="+jobID);
}
An example of the value for 'desc' that I'd want to send is:
80-0234-1 6'5" GATE
So it's a combination of numbers, letters, and special characters.
I tried to replace each of them but it didn't work out.
Any ideas?
Use encodeURIComponent()
function insertJobDesc (r) {
rowid=r;
var qty = document.getElementById('Qty' + r).value;
var desc = encodeURIComponent(document.getElementById('Desc' + r).value);
sendAsync("editDatabase.php?sql=UPDATE+jobdesc+SET+qty="+qty+",+description='"+desc+"',+rowID="+rowid+"+WHERE+id="+rowid+"+AND+jobID="+jobID);
}
Disclaimer: Don't ever do anything like this...
I have a query like this.
SELECT * FROM player_details where name in ('messi','neymar','suarez','alves')
I want to execute this query in titanium.
I tried like this
var in = ['messi','neymar','suarez','alves'];
db.execute('SELECT * FROM player_details where name in ?',in);
But above code producing error.
How can i add IN and NOT IN condition in sqlite in titanium ?
A single parameter ? replaces a single expression.
When you have four values, you need four parameters:
db.execute('SELECT * FROM player_details where name in (?,?,?,?)', in);
If the length of the array is dynamic try something like this:
var params = ["messi", "neymar", "suarez", "alves"],
qMarks = new Array(params.length).join("?,") + "?";
db.execute("SELECT * FROM player_details WHERE name in (" + qMarks + ");", params);