Link to home
Start Free TrialLog in
Avatar of kgp43
kgp43Flag for Denmark

asked on

While loop to check if a value exist in my table

Hi,

I have a problems with a loop, cant finish it.
I have a function which create a random string, this is my "sitekey" which needs to be unique.

The loop need to create and check if the key exist, the loop will stop as soon it have create a key which does not exist in the table.

This is what I have atm:

// Create unique SiteKey
                  while( 1 == 1 ) {
                        
                        $sitekey = randomstring(25);
                        
                        $result = mysql_query("SELECT sitekey FROM sites WHERE sitekey = '$sitekey' ");
                        $count = mysql_num_rows($result);
                        
                        if($count == 0)  {
                        
                              return $sitekey;
                              end;
                        }
                  }
Avatar of teedo757
teedo757

while( $count != 0) {
                       
                        $sitekey = randomstring(25);
                       
                        $result = mysql_query("SELECT COUNT FROM sites WHERE sitekey = '$sitekey' ");
                        $count = mysql_num_rows($result);
                       
                                               }
                            return $sitekey;
                              end;
                  }
Avatar of kgp43

ASKER

This seems to work.
500 points to the first one who confirm :)


// Create unique SiteKey
                  while( true ) {
                        
                        $sitekey = randomstring(1);
                        
                        $result = mysql_query("SELECT sitekey FROM sites WHERE sitekey = '$sitekey' ");
                        $count = mysql_num_rows($result);
                        
                        if($count == 0)  {
                        
                              echo $sitekey;
                              return true;
                        }
                  }
Make sure to initialize the variable before starting the loop

$count = 9
ASKER CERTIFIED SOLUTION
Avatar of teedo757
teedo757

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial