Home > front end >  Checking for existance of value in MySQL
Checking for existance of value in MySQL

Time:07-04

I am developing a user authentication system with expressjs. Therefore to store user data i use a mysql database... When I query to my database I do it with this: SELECT password FROM USERS WHERE email=EmailHere
The problem with this is I dont know an elegant solution to returning an error message if the email doesnt exist. Somewhat understandable?

So to conclude: I want to know if that value exists when I query to the db so I dont get an error message.

Edit:

  const query = `SELECT password FROM USERS WHERE email=?;`;
  let [rows, fields] = await db.promise().query(query, [req.body.email]);

  const password = rows[0].password;
  console.log(password);

This gives me the error: Cannot read properties of undefined reading 'password'.

So it is trying to access the .password column. Can I prevent that?

Thanks in advance! Have a great day

CodePudding user response:

Ok it turns out:

If I check if the length of the rows Array > 0 it fixes the problem. In the else statement I can just log out an error message to say the user does not exist. This could look something like this:

if (!rows.length > 0) return res.status(400).send('User doensnt exist!');
const password = rows[0].password;
// Declaring the variable after I know it exists.

Thanks to @danblack for this answer!

CodePudding user response:

try to change the query like that

SELECT password FROM USERS WHERE email like '%';

or

SELECT password FROM USERS WHERE email='%';
  • Related