简体   繁体   中英

Login works only for last user in the database

For some reason the login only works for the last user in the database. I have a while loop, but I think it makes the program to go to the last user. I tried using if statement but then only the first user can log in.

  if (username!=null && password!=null) {
    pagename = "main";
    } else {
    username = request.getParameter("username");
    password = request.getParameter("password");

            while(results.next()) 
            { 
            if(results.getString(2).equals(password) && results.getString(1).equals(username)) 
            { 
            pagename="main";
            } 
            else 
            { 
            pagename="start";
            } 
    }
  }

How is this caused and how can I solve it?

You are copying the entire DB table into Java's memory and doing the comparison in a while loop over all records. You are not aborting the while loop when there's a match with a record, so it continues looping over the remaining records and so the pagename get overridden with "start" everytime.

You need to add a break statement:

if (results.getString(2).equals(password) && results.getString(1).equals(username)) { 
    pagename="main";
    break;
}

Or, better, let SQL do the job it is designed for, selecting and returning exactly the data you need:

preparedStatement = connection.prepareStatement("SELECT id FROM user WHERE username=? AND password=MD5(?)");
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
resultSet = preparedStatement.executeQuery();

if (resultSet.next()) {
    pagename = "main";
}
else {
    pagename = "start";
}

That's more efficient and sensible.

Why would you loop through the whole table to do this? What if you have 1000000 records? You should query the database with WHERE clause passing the username and password parameters and then simply check if there are returned row or not.

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