I'm focusing on a WordPress wordpress plugin and i'm trying to develop a unique "pin" when adding a row towards the table. The pin must be several string (8 chars but that is not important). The table helps you to save some user data and dates.

But things i am battling with is ensuring I've got a unique pin before placing the row. To date I've attempted utilizing an if statement, but which will only work when the random pin is matched up once.

I am using mt_rand to determine the "pin" after which checking the DB to ascertain if this pin is available (it should be unique). I believe I have to perform a for loop, however i battling (only ever used foreach lopps)

To date I've this, however i know it isn't right (it might work, however i would multiple nested ifs and it might be restricted to the quantity of ifs in position):

function pin_generator_create_pin(){
  global $wpdb;
   $pin = mt_rand(109076, 999999);

   if(!$wpdb->get_var("SELECT * FROM ".PIN_GENERATOR_TABLE." WHERE pin=".$pin)){
     return $pin;
   }else{

     $pin = mt_rand(109076, 999999);
       if(!$wpdb->get_var("SELECT * FROM ".PIN_GENERATOR_TABLE." WHERE pin=".$pin)){
       return $pin;
       }
   }
}//function

Can anybody see what I am attempting to do?

Help please.

You should utilize some time loop, something of that nature:

function pin_generator_create_pin(){
    global $wpdb;

    $pin = 0;
    $pinExists = true;
    while ($pinExists) {
        $pin = mt_rand(109076, 999999);
        if(!$wpdb->get_var("SELECT * FROM ".PIN_GENERATOR_TABLE." WHERE pin=".$pin))
            $pinExists = false;
    }

    return $pin;
}//function