Nodejs | add table columns and values conditionally in sql query statment - mysql

I want to simplify my mysql queries. Here is my current query where I need to include columns conditionally and so there values:
const hasPassword = false;
const myEmail = xyz#yopmail.com;
const myPassword = 123456;
query("SELECT id, name, email, status, (hasPassword ? 'password ,' : '') FROM users WHERE email=${myEmail} (hasPassword ? 'AND password=${myPassword}' : '')"
How to write simplified query similar to the below format:
query("SELECT id, name, email FROM users email=? AND password=?",[email, password]);

Related

putting vars in sql query

New to Node development.
How do you put a variable in a sql query for the VALUES part. Here is what I have. Let me know if it will work.
let email = req.body.email;
let number = req.body.number;
var sql = "INSERT INTO userdata (email, number) VALUES (email, number)";
Thanks
Also, second question. is there anyway I can check if a record already exists with the same email or number within the one sql statement.
According documentation, You should to use parametrized query like:
const email = req.body.email;
const number = req.body.number;
const sql = "INSERT INTO userdata (email, number) VALUES (?, ?)";
connection.query(sql, [ email, number ],
function (err, results) {
}
);
About second question: If you want to your table will have unique records fro each email/number pair you should to add unique index based on those fields.

Loopback 3 pure SQL query with params not working with question marks (with Solution)

My query was like:
let query = `SELECT id, name FROM students WHERE school_code = "${schoolCode}" AND name REGEXP "${text}" `;
And with params:
let params = [ schoolCode, text ];
let query = `SELECT id, name FROM students WHERE school_code = "?" AND name REGEXP "?" `
Model.dataSource.connector.query(query, params, (err, res) => {} );
And it wouldn't work
(Solution below)
I thought maybe it was the REGEXP but
The Solution Was:
to remove quotes around the question marks.
e.g., this worked:
let params = [ schoolCode, text ];
let query = `SELECT id, name FROM students WHERE school_code = ? AND name REGEXP ? `
Model.dataSource.connector.query(query, params, (err, res) => {} );

Mysql: which fields matched using "OR"

I have this query:
SELECT * FROM accounts WHERE username = "aaa" OR email = "abc#example.com" OR mobile = "123456789"
I can find which field did match like this:
var username = req.body.username;
var email = req.body.email;
var mobile = req.body.mobile;
database.query("SELECT * FROM accounts WHERE username = ? OR email = ? OR mobile = ?",[username, email, mobile, (err, result)=>{
if (result.username == username) {...}
if (result.email == email) {...}
if (result.mobile == mobile) {...}
}
But, I'd like to know which field did match without using if multiple times (if possible). So, is that possible form within Mysql only?
You can put it in the SELECT list. You can use CONCAT_WS() to combine the list of columns into a comma-separated list. It will omit NULL values, so this will just list the matched fields.
database.query(`SELECT *,
CONCAT_WS(',',
IF(username = ?, 'username', NULL),
IF(email = ?, 'email', NULL),
IF(mobile = ?, 'mobile', NULL)) AS matched_fields
FROM accounts WHERE username = ? OR email = ? OR mobile = ?`, [username, email, mobile, username, email, mobile], (err, result) => {
var matched = result.matched_fields.split(',');
matched.each(field => {
switch(field) {
case 'username': ...; break;
case 'email': ...; break;
case 'mobile': ...; break;
});
})
Create custom column in select query and that custom column has case statement with three column(username, email, mobile) matching and print respective flag in that custom column to let it know that row comes from based on which condition.
Try Below:-
SELECT * FROM accounts WHERE (username = "aaa" OR email = "abc#example.com" OR mobile = "123456789")
Whichever field has first match then your condition become true and it will return result. If you want to match all the condition then you should use AND operator

How to create an sql statement with optional parameters

I have a lessons table that contains the following fields:
id title type language level
The user through the interface can select witch lesson he wants to open.
He will start selecting the language, then the type and finally the level.
During this process I want to query the database using a single sql statement, but of course the first query will have only the language field. I came up with this syntax but it does not work:
function queryLessonList (language, type, level){
const values = [language, type, level];
const sql = "SELECT * FROM lessons WHERE (language=?) AND (? is null OR type=?) AND (? is null OR level=?)";
return query(sql, values);
}
How can I make it work?
To reduce the complexity of checking variables and building out the query, instead you can pass the function an object to match, what you want and the columns you want returning etc (as * is not ideal).
So something like:
function queryLessonList (where = {}, columns = ['*']) {
let keys = Object.keys(where)
let values = Object.values(where)
columns = !columns.length || columns[0] === '*' ?
'*': columns.map(e => '`'+e+'`').join(',')
let sql = `
SELECT ${columns}
FROM lessons
${keys.length ? 'WHERE \`'+keys.join('` = ? AND `')+'\` = ?' : ''}
`
return query(sql, values)
}
/*
SELECT *
FROM lessons
WHERE `language` = ? AND `type` = ?
*/
queryLessonList({
language: 'en',
type: 'foo'
}, [])
/*
SELECT `id`
FROM lessons
*/
queryLessonList({}, ['id'])
/*
SELECT *
FROM lessons
*/
queryLessonList()

How to write OR condition in Select Query

Is there a way in mysql to express 'OR' ? The idea is to search if there is a match "user.getinput()" that corresponds to the username column or the email column. How to express this in a proper way.
SELECT FROM tablex WHERE username OR email = '"+ user.getinput()+"'";
The following is the query:
SELECT FROM tablex WHERE username = ? OR email = ?
Better use PreparedStatement
String query = "SELECT FROM tablex WHERE username = ? OR email = ?";
PreparedStatement stmt=con.prepareStatement(query);
stmt.setString(1,userName);
stmt.setString(2,email);
stmt.executeUpdate();
I strongly recommend to use a prepared statement to prevent sql injection issues.
Something like this:
PreparedStatement stmt = conn.prepareStatement(
"SELECT * FROM tablex WHERE username = ? OR email = ?");
stmt.setParameter(1, "something");
stmt.setParamater(2, "something");