1) The first bug is that you never submit the query to the DBMS - your code should look something like:
$dbh=mysql_connect(...);
mysql_select_db(...,$dbh); // note see below
$result=mysql_query(....$dbh);
while ($row=mysql_fetch_assoc($result)) {
...
}
2) You've got 2 loops (a for loop and a while loop) around the code which retrieves rows from the query - there should only be one. So if your query returns 3 rows, you actually loop around 9 times:
1) for loop iteration 1
2) while loop iteration 1 fetches row 1, writes results
3) while loop iteration 2 fetches row 2, writes results
4) while loop iteration 3 fetches row 3, writes results
5) while loop fails on subsequent iteration
6) for loop iteration 2
7) while loop fails on subsequent iteration
8) for loop iteration 3
9) while loop fails on subsequent iteration
3) You assign the values returned by the mysql_fetch_assoc to scalar variables (i.e. you overwrite te result each time - so $user and $pass always contain the values from the last row returned.
4) Its good practice to establish early exit criteria within a loop - in addition to avoiding redundant execution, this would also solve the 3rd bug described above, e.g.
$valid=false;
while($row=mysql_fetch_array($result))
{
if (($username==$row['UNAME']) && ($password==$row['PW'])) {
$valid=true;
break;
}
}
if ($valid) {....
4) The next problem is why are you checking if the username matches $username when you've previously said it should be the same as $_POST['Uneym'].
5) The next problem is that you seem to have written this code with register_globals enabled.
6) The next problem is that you are needlessly fetching data from the database - just add a filter on the password then you'll only get 1 or zero rows (and you don't even need to iterate through the result set):
$user=mysql_real_escape_string($_POST['Uneym'], $dbh);
$pass=mysql_real_escape_string($_POST['password'], $dbh);
$result=mysql_query("SELECT * FROM users WHERE UNAME='$user' AND PW='$pass'",$dbh);
$valid=mysql_num_rows($result);
and still there's more:
7)
if($username == $user && $password ==$pass)
{
echo "alert('Login Successful!')";
}
else if($password!= $pass ||$username != $user )
{
echo("Please Enter Correct Username and Password ...");
?>
This will not parse - there's an unmatched '{' after the else
8) The condition in the else statement is redundant - the code will only ever go into the else clause if it fails the if clause, and by definition,
($username == $user && $password ==$pass) === ! ($password!= $pass ||$username != $user )
9) using mysql_select_db() can make life very complicated if you are working with multiple mysql databases - in general its a better idea to exlpicitly state which database a table resides in with the DML statement.
C.