memberlogin
contactus
randomfacts

Looping through a resultset and setting session variables

The example below shows a member login authorization script.  It\'s not the best way to illustrate how to loop through a resultset using php, but it does get the idea accross.  First you connect to the database using the username, password, server_name, and database name.  Then you query a table for general or specific data ( in this example my resultset is named $result2.  Then I grab the row count returned from my query and set that value to the variable $num2.

Now if the value of $num2 is 0 - meaning that no records were found for my query then I redirect them to the login screen (for this example).  Otherwise if rows are returned then I do a while loop as long as $i which starts at 0 is less than the number or rows returned from the query ($num2).  I grab the values by using the mysql_result function which takes as parameters the resultset name, the row to grab, and the column name.

I set the register and set the session variables userid and emailaddress and I redirect them to the main members screen index.cfm.

******Make sure that you increment $i when doing these loops - otherwise your in an infinite loop and it\'s not nice to be those.

<?
 $username = "db_username";
 $password = "db_password";
 $database = "db_name";
 mysql_connect("db_server_address",$username,$password);
 @mysql_select_db($database) or die( "Unable to select database");
 
 $strSQL = "select * from users where username = \'".$username."\' AND password=\'".$password."\'";
 $result2=mysql_query($strSQL);
 $num2 = mysql_numrows($result2);
 
 if($num2 == 0){
  header("Location: members/login.php?login_error=true");
 } else {

 $i = 0;
  while ($i < $num2) {
   session_register("userid"); 
   session_register("emailaddress");
   $userid = mysql_result($userid_rs,$i,"user_id");  
   $emailaddress=mysql_result($result2,$i,"email_address");
   $i++;
  }
  header("Location: members/index.php");
 }
?>