Reputation: 23
I'm making a simple node.js webapp for inserting data into a database with a condition - when there's two instances with the same time attribute, the insert query isn't called and you get redirected to a simple html page with a message that you have to pick another time.
My question is, how can I redirect from a block of code belonging to query? or is there another way to let user know that he has to pick another time?
app.post('/', function(req, resp) {
try {
var name = req.body.name;
var date = req.body.date + " " + req.body.time;
var phone = req.body.phone;
var spz = req.body.spz;
var typeOfProblem = req.body.typeOfProblem;
con.query(("SELECT COUNT(*) AS datecheck FROM `objednani` WHERE datetime = '"+ date +"'"), function(err, result){
if (err) throw err;
if(result[0].datecheck > 1){
console.log("preplneno"); // THIS IS THE POINT WHERE I WANT TO REDIRECT THE USER
} else {
con.query(("INSERT INTO objednani (name, datetime, phone, spz, typeofproblem) " + "VALUES ('"+name+"','"+date+"','"+phone+"','"+spz+"','"+typeOfProblem+"')"), function (err, result) {
if (err) throw err;
console.log("uspech");
});
}
});
} catch (err) {
resp.redirect('/fail');
}
});
Upvotes: 2
Views: 195
Reputation: 787
You can call resp.redirect('/fail');
inside your query block, or anywhere in function(req, resp)
function. You don't need to throw and catch.
As another suggestion: you can try parameter embedding for your sqls. otherwise you can be subject to sql injection attacks.
Upvotes: 1