Daniel Costello
Daniel Costello

Reputation: 80

Express + Passport : How to use req.user variable in MYSQL query

I hope someone can help with. Apologies if its simple, I've been searching the web for hours and havn't round the right answer.

I'm using Express with Passport. I have logins working and req.user is being populated with the user_id from the database which comes out in this format when console.log'ing it:

req.session.passport.user: {"user":{"user_id":18} }

So that's good. Now I'm moving onto another page and trying to use that variable in a new MYSQL query to get more information from the user out of my database like so:

user = req.user;
db.query("SELECT * FROM users WHERE id = 'user'", function(error, results, fields) {
        if (error) throw error;
        console.log(results)
      });

I can't get this to work after trying to strip the user_id variable down to just numbers, etc. Can anyone suggest a method to get the req.user variable into a usable format fitting a MYSQL query (being just the number so I can match it against the proper field)? Any assistance would be greatly appreciated. Thanks for reading!

Regards, Daniel

Upvotes: 0

Views: 348

Answers (1)

0xdw
0xdw

Reputation: 3842

You can use template literal just as follow,

db.query(`SELECT * FROM users WHERE id = ${req.user.user_id}`, function(error, results, fields) {
  if (error) throw error;
  console.log(results)
});

Or

"SELECT * FROM users WHERE id =" + req.user.user_id

Upvotes: 1

Related Questions