我正在使用NodeJs和MySQL创建用户登录/注册以在Android学校项目中使用,但是不确定如何检查用户是否已经存在相同的电子邮件。
下面是我的代码。
ps,我将对密码进行哈希处理。
// registration
router.post('/register', (req,res)=>{
const name = req.body.name;
const email= req.body.email
const phone= req.body.phone;
const password= req.body.password;
const password2 = req.body.password2;
let errors = [];
//Check required fields
if(!name || !email || !phone || !password || !password2){
errors.push({msg: 'Please fill in all the fields'});
res.send({message:'Please fill in all the fields'});
}
//Check passwords match
if(password != password2){
console.log('Passwords dont match');
errors.push({msg: 'Passwords dont match'});
res.send({message:'Passwords dont match'});
}
//Check password length
if(password.length < 6){
errors.push({msg: 'Password should be atleast 6 characters'});
res.send({message:'Password should be atleast 6 characters'});
}
if(errors.length>0){
}else{
connection.query('INSERT INTO users(name, email, phone, password) VALUES("'+name+'", "'+email+'", "'+phone+'", "'+password+'")',
[name, email, phone, password]);
res.send('Welcome');
}
});
module.exports = router;
请帮助
答案 0 :(得分:0)
代替此代码:
connection.query('INSERT INTO users(name, email, phone, password) VALUES("'+name+'", "'+email+'", "'+phone+'", "'+password+'")',
[name, email, phone, password]);
您可以这样做:
connection.query('SELECT email FROM users WHERE email ="' + mysql.escape(email) +'"', function (err, result) {
if (err) throw err;
console.log(result);
//You will get an array. if no users found it will return.
if(result[0].email.length > 0){
//Then do your task (run insert query)
connection.query('INSERT INTO users(name, email, phone, password) VALUES("'+name+'", "'+email+'", "'+phone+'", "'+password+'")',
[name, email, phone, password]);
res.send('Welcome');
}
});