Reputation: 171
Im creating a user login/registration using NodeJs and MySQL to use on an Android school project, however am not sure how to check if a user already exists with the same email.
Below is my code.
ps I will hash the passwords.
// 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;
Please help
Upvotes: 0
Views: 3438
Reputation: 54
Instead of this code:
connection.query('INSERT INTO users(name, email, phone, password) VALUES("'+name+'", "'+email+'", "'+phone+'", "'+password+'")',
[name, email, phone, password]);
You can do by this:
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');
}
});
Upvotes: 1