Forum Moderators: coopster

Message Too Old, No Replies

A brief question on the WHILE loop

         

nshack31

9:16 pm on Jan 4, 2005 (gmt 0)

10+ Year Member



ok first here is my code to check the user login name etc, I have highlighted the part i wish to draw your attention to in bold...

<?php
$conn=odbc_connect('league','','');
$me=$_REQUEST['username'];
$pass=$_REQUEST['password'];

if (!$conn)
{
exit(
"Connection Failed: " . $conn);
}
$sql="SELECT * FROM users WHERE username = '$me' AND password = '$pass'";
$rs=odbc_exec($conn,$sql);
if (!$rs)
{
exit("Error in SQL");
}
while (odbc_fetch_row($rs))
{
$username=odbc_result($rs,"username");
$password=odbc_result($rs,"password");

if ($username == $me && $password == $pass)
{
setcookie ("username", $username,time()+3600);
header ('location: index.php');
}
else
{
header ('location: error.php');
}
}
odbc_close($conn);
;?>

my question is this, what does that part do?! if i remove the while loop then it still works fine! Therefore why is it used?! thanks

Salsa

9:46 pm on Jan 4, 2005 (gmt 0)

10+ Year Member



You don't need the while loop if you are returning only one row, as you are in your example. But, for example, if you didn't use the WHERE clause in your query, the query would return all the rows from users, and the while loop would allow you to process them one row at a time.

I hope this helps.

mcibor

10:42 pm on Jan 4, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You should get rid of that while -> change it to if, if you want.

Otherwise it is unsafe.
Eg.There was once a user jake with pass jake. But then there came another user jake with pass jacob.

Your code will allow both of the users to login, whether it shouldn't usually be possible.

While is a loop and is being done as long as value in brackets is true.

Hope it cleared the topic a little!

nshack31

11:38 pm on Jan 4, 2005 (gmt 0)

10+ Year Member



thanks for that! one other question, inn what circumstances then would the loop be required?

dreamcatcher

11:45 pm on Jan 4, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi nshack31,

If you wanted to return more than one row, you would use a while loop. As Salsa mentioned, its not needed for returning one row. If you had say 10 rows, a while loop would execute until all rows are fetched. In this case, 10 times. ie: 10 loops.

dc