I'm trying to check if a user in the database also exists. My code works if I add a user to the db without checking if someone with it's name exists. The problem appears when I try to check it, because the code can recognize if a user exists or not, but the user cannot be added to the database if this doesn't exist. The code which works is this one (the function DB() is where the code creates the connection with the database):
app.post('/Registro', function(req, res){
var conDB=DB();
var reg={
Usuario: req.body.Usuario,
Contra: req.body.Contra
};
console.log(req.body.Usuario+" "+req.body.Contra);
var query=conDB.query('INSERT INTO Usuario SET ?',reg,function(err, res){
});
res.send("Usuario: "+req.body.Usuario+" y Contraseña: "+req.body.Contra + "REGISTRADOS");
conDB.end(); });
The code which doesn't work (where I'm trying to check if the user exists) is this one:
app.post('/Registro', function(req, res){
var conDB=DB();
var reg={
Usuario: req.body.Usuario,
Contra: req.body.Contra
};
var UsuarioReg=req.body.Usuario;
conDB.query('SELECT * FROM Usuario WHERE Usuario = ?', UsuarioReg,function(err,rows){
if(err)
return console.log(err);
if (!rows.length)
{
conDB.query('INSERT INTO Usuario SET ?',reg,function(err, respuesta){
return respuesta.send("Usuario: "+req.body.Usuario+" y Contraseña: "+
req.body.Contra + "REGISTRADOS");
});
}
else
{
return res.send("Este usuario ya existe");
}
});
conDB.end();
});
If someone knows how can I solve this situation, I'd be grateful!
I have made an edition which threw this exception:
