SELECT query from mysql with node js (LIKE query) - mysql

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 }) }

Related

Nodejs and SQL - Issue with inserting data to SQL using multiple select statements

Error image
While inserting the data in SQL database table user_recipe_consumption by using multiple select statements i am facing error as - throw err; // Rethrow non-MySQL errors
^
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 'Mushroom pasta');' , '( select vegEmission from RecipeEmissions where RecipeName' at line 1
for (var dataVal = 0; dataVal < req.body.length; dataVal++) {
var recipeInfo = req.body[dataVal].RecipeName;
var deviceID = req.body[dataVal].deviceID;
var totEmission = req.body[dataVal].totalEmission;
var sql = "INSERT INTO user_recipe_consumption (deviceID, totalEmission, recipeID , vegEmission,date_of_entry) VALUES ('" + deviceID + "','" + totEmission + "', '( select RecipeID, from RecipeEmissions where RecipeName = ?);' , '( select vegEmission from RecipeEmissions where RecipeName = ? );' ,'" + now + "')";
con.query(sql, recipeInfo, function(err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
}
Instead of SQL with var concated (and related problem with data type and SQL injection) you should use a query completely based on param binding (eg: named param). You should also use a insert select syntax instead of several select from the same table
"INSERT INTO user_recipe_consumption (deviceID, totalEmission, recipeID , vegEmission,date_of_entry)
SELECT :deviceID, :totEmissino, RecipeID, vegEmission, :date_of_entry
FROM RecipeEmissions
where RecipeName = :RecipeName;"
eg:
connection.execute(
"INSERT INTO user_recipe_consumption (deviceID, totalEmission, recipeID , vegEmission,date_of_entry)
SELECT :deviceID, :totEmission , RecipeID, vegEmission, :date_of_entry
FROM RecipeEmissions
WHERE RecipeName = :RecipeName;",
{deviceID: deviceID, totEmission: totEmission, date_of_entry:date_of_entry,RecipeName:RecipeName},
function(err, result)
.......
You have too many semicolons in your SQL statement. You're also putting single-quotes around a subquery, which effectively turns it into a string literal. And you're using NOW() incorrectly. Try this:
var sql = "INSERT INTO user_recipe_consumption (deviceID, totalEmission, recipeID , vegEmission,date_of_entry) VALUES ('" + deviceID + "','" + totEmission + "', ( select RecipeID, from RecipeEmissions where RecipeName = ?) , ( select vegEmission from RecipeEmissions where RecipeName = ? ) , NOW())";
If you mean now to be a JS variable then you can revert that part of the query to what you had originally, but it's not clear what now is supposed to contain.

MySQL condition depending on column value

So, I have more or less this structure of columns in my table:
Name Age Operator
---- --- --------
Jhon 35 >
Michael 30 =
Jess 27 <
Based on that I want to make a query like this
SELECT * FROM mytable WHERE Name = 'John' AND Age > 40
obviosly this will return no results, and thats fine, but my problem is that I want to use Jhon's "Operator" value (> in this case) to make that condition.
Is it possible?
Thank you!
You can simply do it like this:
SELECT
*
FROM Table1
WHERE Name = 'Jhon'AND CASE
WHEN Operator = '>' THEN Age > 10
WHEN Operator = '<' THEN Age < 10
WHEN Operator = '=' THEN Age = 10
END
see it working live in an sqlfiddle
You also could use MySQL's PREPARE and EXECUTE statements to make dynamic SQL.
SET #name = 'Jhon';
SET #operator = NULL;
SET #age = 10;
SELECT
Operator
INTO
#operator
FROM
Table1
WHERE
Name = #name;
SET #SQL = CONCAT(
"SELECT"
, " * "
, " FROM "
, " Table1 "
, " WHERE "
, " name = '", #name, "' AND age ", #operator, ' ' , #age
);
SELECT #SQL; # not needed but you can see the generated SQL code which will be executed
PREPARE s FROM #SQL;
EXECUTE s;
see demo https://www.db-fiddle.com/f/3Z59Lxaoy1ZXC4kdNCtpsr/1

Make MySQL's ORDER BY dynamic in node.js

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});

Build complex query in laravel 5

I want to build query after in laravel 5
SELECT * FROM tbl WHERE updated_at IN (
SELECT max(updated_at) FROM tbl
WHERE created_at BETWEEN $begin_time AND $end_time
GROUP BY ip_address)
My code:
$sqlStr = self::select('*')
->whereIn('updated_at', function($query){
return $query->select(self::raw('max(updated_at)'))
->whereRaw('created_at >= $begin_time)
->whereRaw('created_at <= $end_time)
->groupBy('ip_address');
})->toSql();
var_dump(($sqlStr));die;
Error information:
ErrorException in Grammar.php line 58:
strtolower() expects parameter 1 to be string, object given
Please help me.
When you wrote self::raw('max(updated_at)') that generates SELECT max(updated_at) FROM tbl which is already inside a select command. Following code will work:
$sqlStr = self::select('*')
->whereIn('updated_at', function($query) {
$query->selectRaw('max(updated_at)')
->from('tbl')
->whereRaw('created_at >= $begin_time')
->whereRaw('created_at <= $end_time')
->groupBy('ip_address');
})->toSql();
Or this should work too:
DB::select(
'SELECT * FROM tbl WHERE updated_at IN (' .
'SELECT max(updated_at) FROM tbl ' .
'WHERE created_at BETWEEN :begin_time AND :end_time ' .
'GROUP BY ip_address '
')',
[
'begin_time' => $begin_time,
'end_time' => $end_time
]
);

Adding string as a part of query in jdbcTemplate call in MySQL

I have a query and a few parameters as follows,
String query = "SELECT * FROM table_name ORDER BY ? LIMIT ? ";
//I am creating this 'sortString' on runtime based on some user inputs
String sortString = " column1 ASC, column 2 ASC ";
int count =5;
I am calling the jdbcTemplate method as follows,
List<Map<String, Object>> rows = getJdbcTemplate().queryForList(query, sortString, count);
The query that is actually used by the jdbcTemplate is as follows,
SELECT * FROM table_name ORDER BY ' column1 ASC, column 2 ASC ' LIMIT 5
Now, the ORDER BY clause does not works since the criteria is put up inside ' ' by jdbcTemplate. How can I add the string to the query without the jdbcTemplate adding the " ' " by default.
I want the query to be,
SELECT * FROM table_name ORDER BY column1 ASC, column 2 ASC LIMIT 5
You cannot use a prepared statement, when you generate a whole part of the query dynamically. The ? in a prepared statement always stands for a value.
//I am creating this 'sortString'
String sortString = " column1 ASC, column 2 ASC ";
String query = "SELECT * FROM table_name ORDER By " + sortString + " LIMIT ? ";