简体   繁体   中英

Checking if email id already exists in database using JSP

I want that a particular email id shouldn't be used more than once when doing registration. Here's my code:

if(request.getParameter("btn1")!=null)
  {
      String unm=request.getParameter("nm");
      String em=request.getParameter("email");
      String pwd=request.getParameter("pass");
      Connect c1=new Connect();
       String q="insert into register(name,email,password) values('"+unm+"','"+em+"','"+pwd+"');";
    int rs=c1.DMLExecuter(q);
    if(rs>0)
    %>
    <script>
        alert("You are registered now. Please login to continue.");
    </script>

What should I do to check if the email id is being used twice?

  1. ensure that your email field is unique, such as by adapting the DDL accordingly (this will get the database to ensure that e-mail addresses are unique). Alternatively, the e-mail field could be made primary key:

     CREATE TABLE register( ... EMAIL VARCHAR(50) NOT NULL UNIQUE, ... ) 
  2. In the code, before inserting, check the count of existing e-mails by that ID:

     long existingCount = ... String countQuery = "SELECT COUNT(1) FROM register WHERE email = ?" 

Run this query with the value of request.getParameter("email") . The result should be a number telling you the number of existing users with that e-mail.

Assuming that count has been stored in the existingCount variable:

if(existingCount == 0) {
    //Put here the code to insert the new user as shown in your question...
} else {
%>
    <script>
        alert("You are already registered. Login or choose a different email");
    </script>
<%
}

Note that my sql used bind variables , please use a prepared statement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM