To allow users to login using thier username
or email
OR phonenumber
, I’m using this query:
res.post('/api/userlogin', function(req, res){ connection.query( 'SELECT * FROM users WHERE username=? OR email=? OR phonenumber=? AND password=?', [req.body.loginfield, req.body.loginfield,req.body.loginfield, req.body.password], function(){ ... ... //res.send }); });
I beleive this is how mysql work, but I thought maybe there is a way to use only one value (req.body.loginfield
) for multiple placeholder without typing it repeatedly.
I couldn’t find anything about it in the docs though.
Advertisement
Answer
You can use the IN
operator:
SELECT * FROM users WHERE ? IN (username, email, phonenumber) AND password = ?
Side note: your original query has a prescendence issue, which makes it quite unsafe. As it is, this will authorize users that login using their username or email without checking their password, since this:
username=? OR email=? OR phonenumber=? AND password=?
Is syntaxically equivalent to:
(username=? OR email=?) OR (phonenumber=? AND password=?)
This is because logical operator OR
has lower prescedence than AND
. You would need to surround the OR
ed conditions with parenthesis, as follows:
(username=? OR email=? OR phonenumber=?) AND password=?)