On Tue, Aug 10, 2010 at 10:18 AM, Tomfox Wiranata <tomfox.wiran...@gmail.com> wrote: > hi, > > i need to check if a specific, randomly generated number already > exists in the database. when it does exist, a new number needs to be > created and checked too. until there is a number, that doesn't exist > already.. > > the check in my model for existance: > > function validatenumber($data) > { > $test = $this->find(array('number' => $data), array('user_id')); > > if(empty('test') == true) > return true; > return false; > } > > now i can make a working check, but only once in my controller: > > $x=rand(10,100000); > > if($test=$this->Linkable->validatenumber($x) == true) > { > return $x: > }else{ > .... > } > > > but how can i make a loop to create numbers as long as one is not > already taken? is there sth like a for loop? havent seen anything like > that yet
Use the do {} while() construct. public function getNewNumber() { /* fetch all existing numbers */ $numbers = $this->find( 'list', array( 'fields' => array( 'Linkable.number' ) ) ); /* create new number; check exists; repeat if necessary */ do { $new_number = rand(10,100000); } while (in_array($new_number, array_values($numbers)); return $new_number; } So, in the controller, you could assign the number with a single call to $this->Linkable->getNewNumber() and be done with it. I didn't quite understand your find() code. I think what I have above should maybe work, though. Check out the new CakePHP Questions site http://cakeqs.org and help others with their CakePHP related questions. You received this message because you are subscribed to the Google Groups "CakePHP" group. To post to this group, send email to cake-php@googlegroups.com To unsubscribe from this group, send email to cake-php+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php?hl=en