Jump to content

whlie loop


dan_t

Recommended Posts

This is probably a simple question, but if you are looping through a while loop using an if - else statement

why would it echo the answer the amount of times there are data fields?

Like if you had three users in a database and you had an if statement to validate a user name and password. If the user name and password passed it would say good - if it failed it would say no good.

But instead it prints - good no good good, or no good good good, ect.??? >:(

Link to comment
Share on other sites

This is on of the hundred ways I have tried it:

$query = "SELECT username, password FROM userTable";

	$result = mysql_query($query);

	while($row = mysql_fetch_array($result)) {
		$logged = (($row['username'] == $username) && ($row['password'] == $password));

			if(!$logged){
				echo "Sorry";
			} else {
				echo "Good!";
			}

 

I also tried a switch statement, but have become frazzled.

Link to comment
Share on other sites

If you only want records where the username & password match those in the DB, do that via the query:

<?php
$query = "SELECT username, password FROM userTable where username='$username' and password='$password'";
?>

This assume that the values of $username & $password have been properly sanitized.

 

Ken

Link to comment
Share on other sites

You just have to break the loop once found. Better yet, change your SQL to get the password from the database using the username.

 

Instead of

<?php
$query = "SELECT username, password FROM userTable";

	$result = mysql_query($query);

	while($row = mysql_fetch_array($result)) {
		$logged = (($row['username'] == $username) && ($row['password'] == $password));

			if(!$logged){
				echo "Sorry";
			} else {
				echo "Good!";
			}
                        }
}

   

Do this:

<?php
$sql = 'SELECT `password` FROM `userTable` WHERE username = \'' . $username . '\'';
$query = mysql_query($sql);
if(mysql_num_rows($query) < 1) { // If there are no results found with that username, tell the user
    echo 'Incorrect Username';
} else { // Use and else statement so that it doesn't give errors when checking the password (no result means no password to check)
    $result = mysql_result($query);
    if($result != $password) {
        echo 'Incorrect Password';
    } else {
        echo 'Login Success!';
    }
}

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.