简体   繁体   English

检查 MySQL 中是否存在值

[英]Checking for existance of value in MySQL

I am developing a user authentication system with expressjs.我正在使用 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因此,为了存储用户数据,我使用 mysql 数据库......当我查询我的数据库时,我这样做: 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.问题是如果 email 不存在,我不知道返回错误消息的优雅解决方案。 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.所以它试图访问.password 列。 Can I prevent that?我可以防止吗?

Thanks in advance Have a great day提前谢谢祝你有美好的一天

Ok it turns out:好的,事实证明:

If I check if the length of the rows Array > 0 it fixes the problem.如果我检查行 Array > 0 的长度是否可以解决问题。 In the else statement I can just log out an error message to say the user does not exist.在 else 语句中,我可以只注销一条错误消息,说用户不存在。 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感谢@danblack 的回答

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM