Sri Sai Ramya T
Sri Sai Ramya T

Reputation: 59

Check email exists in mysql database or not with nodejs

Need to check email is exists or not in mysql when user enters in the form. From form requser.email will have user emaild entered in form. How to compare requser.email with database to find match.

 router.post('/signup', function(req, res, next) {
    var requser = req.body.data.user;
  var hash = bcrypt.hashSync(req.body.data.user.password)
  var str = "";

  /*email check start*/

  /*email check end*/
  switch (requser.role) {
    case "approver":
      str = 'INSERT INTO users (name, email, password,role) values("' + requser.name + '","' + requser.email + '","' + hash + '","approver")';
      break;
    case "user":
      str = 'INSERT INTO users (name, email, password,role) values("' + requser.name + '","' + requser.email + '","' + hash + '","user")';
      break;
    case "admin":
      str = 'INSERT INTO users (name, email, password,role) values("' + requser.name + '","' + requser.email + '","' + hash + '","admin")';
      break;
  }
  if (!str) {
    return res.json({
      "status": "error",
      "data": {
        "redirect": "/"
      }
    });
  }
  connection.query(str, function(error, rows) {
    if (error) {
      console.log("error ocurred", error);
    }
    //console.log(rows);
    res.json({
      "status": error ? "error" : "success",
      "data": rows || ""
    })
  });
});

Upvotes: 0

Views: 2023

Answers (1)

Darshan Mehta
Darshan Mehta

Reputation: 30809

You can either write a SELECT 1 query to get the record with that email address or define a UNIQUE CONSTRAINT on email field so that insert would fail.

Here's an example of UNIQUE CONSTRAINT and here's an example of SELECT 1:

SELECT 1 FROM users WHERE email = <email>;

Upvotes: 1

Related Questions