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 <strong>exactly</strong> 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.

人吐槽 人点赞



用户名: 密码:
验证码: 匿名发表


查看评论:Login works only for last user in the database