I'm trying to check in a NodeJS query where a user his id is e.g. 1 and his private_number is 25, the following code doesn't work.
query('SELECT * FROM `users` WHERE `user` = '+pool.escape(user)+', `private_number` ='+pool.escape(number), function(err, row) { //get if the player has a query with the same code
});
Is this even properly possible?
you can use template strings
query(`SELECT * FROM users WHERE user = ${pool.escape(user)} AND
private_number = ${pool.escape(number)}`), function(err, row) {
})
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
P.S. when you have multiple conditions in WHERE clause you need to 'connect' them with logical operator like AND or OR
Related
Hello guys I'm new in using mysql library in node js and I'm interested in possibility of inserting multiple rows at once in database. I've made a simple code which captures user registration id from database table and uses indexes of roles which that user has selected. And now I want to add user and role id into Role_User table which has user_id and role_id respectively.
Let's say I wanna do this 3 times without using loop:
Insert Into User_role VALUES (1,20);
Insert Into User_role VALUES (2,20);
Insert Into User_role VALUES (3,20);
, where numbers 1,2,3 of the first columns are role indexes.
Error I'm getting is RequestError: Incorrect syntax near '?'.
How can I make this query work?
if(req.body.roles){
var sqlQuery = `SELECT ID from Test_user Where email = #email`;
var indexiRola = findPositions(db.ROLES, req.body.roles);
request.input('role', db.sql.NChar, req.body.roles);
request.query(sqlQuery).then(
id => {
let ids = Array(req.body.roles.length).fill(id.recordset[0].ID);
console.log(ids); // [20, 20, 20]
let roleUsers = createSeperateLists(indexiRola, ids);
console.log(roleUsers); // [ [ 1, 20], [ 2, 20], [ 3, 20] ]
var insertQuery = `INSERT INTO Role_User ("role_ID", "user_id") VALUES ?`;
request.query(insertQuery, [roleUsers], function(err, result){
if(err) throw err;
console.log("Successfull insertion");
});
})
}
Check if it helps, please. I cannot check it running, of course.
It's not complete, on the contrary! request.query is async, and that code has to be revised.
At least, this code, as I hope, does not break into RequestError: Incorrect syntax near '?'.
Please:
check if the revision works for one input
whenever you get the complete solution, share it with us
if (req.body.roles) {
var sqlQuery = `SELECT ID from Test_user Where email = #email`;
var indexiRola = findPositions(db.ROLES, req.body.roles);
request.input('role', db.sql.NChar, req.body.roles);
request.query(sqlQuery).then(
id => {
let ids = Array(req.body.roles.length).fill(id.recordset[0].ID);
console.log(ids); // [20, 20, 20]
let roleUsers = createSeperateLists(indexiRola, ids);
console.log(roleUsers); // [ [ 1, 20], [ 2, 20], [ 3, 20] ]
// I removed the double quotes from the names and,
// VALUES (?, ?) - this is the right syntax for SQL
const insertQuery = 'INSERT INTO Role_User (role_ID, user_id) VALUES (?, ?)';
// Then, forEach roleUsers
// By the way, [roleUsers] yields an array of arrays of arrays, not cool
roleUsers.forEach(
roleUser => {
request.query(
insertQuery,
roleUser,
// Oh! Shoot!!! This is async.
// Man, you will have to deal with it.
// Please, share with us the final solution!
function(err, result) {
if (err) throw err;
console.log("Successfull insertion");
}
);
}
);
})
}
I'm trying to save the information I get from my inmatefirst column with my SQL query into the variable "first'. I was wondering what the correct syntax/approach was to doing this.
let sql = `SELECT * FROM inmates WHERE inmatefirst = ? AND inmatelast = ? AND dob = ?`;
let query = db.query(sql, [search.first, search.last, search.dob], (err, result) => {
if (err) throw err;
if (result.length != 0) {
res.render(path.resolve('./myviews/modify'), {
good: 'Person Found - Please Enter Updated Information',
first: result.inmatefirst,
last: result.last,
dob: result.dob,
sex: result.sex
});
});
});
Your SQL says, in part, this:
SELECT * FROM inmates WHERE inma...
You've asked for every column from the table. That can make life confusing.
Instead, spell out the columns you want. Your Javascript indicates that you want these ones:
SELECT inmatefirst, last, dob, sex FROM inmates WHERE inma...
(It's possible that is the wrong set of columns. Check it.
Then, as #barmar pointed out, use result[0].first etc, because result is an array of objects, one for each row of your resultset.
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.
Previous post I will refer to later
I am making a Discord bot which uses MySQL, but that shouldn't matter, I am trying to do a blacklist database so users in it can't use my bot
This is what I got so far:
con.query("SELECT EXISTS( SELECT 1 FROM `blacklist` WHERE `id` = '"+message.author.id+"')", function(error, result, field) {
if(error) throw error;
});
And this kinda works, this is my output
[ RowDataPacket {
'EXISTS( SELECT 1 FROM `blacklist` WHERE `id` = \'227090776172134400\')': 1 } ]
And the last digit works like a boolean, 1 if the row exists, 0 if it does not
But my problem is, that I can't seem to figure out how to check if it's a zero or not because it's an object
Why can't you make the query string a variable that you can later query on. For example:
let conStr = "SELECT EXISTS( SELECT 1 FROM `blacklist` WHERE `id` = '"+message.author.id+"')";
con.query(conStr, function(error, result, field) {
if(error) throw error;
console.log(result[conStr]); //--> 1
});
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)