Page 1 of 1
Check DB, then create random number
Posted: Mon Aug 11, 2014 9:51 pm
by donny
Hello,
can somebody please help me create a random number but it can't exist already in my database.
thank you
Re: Check DB, then create random number
Posted: Mon Aug 11, 2014 10:09 pm
by Celauran
You'll need to be more specific. Start by looking at
rand().
Re: Check DB, then create random number
Posted: Tue Aug 12, 2014 2:49 pm
by donny
this is what i am working with now
Code: Select all
<?php
$random = mt_rand(10000,99999);
echo $random;
$sql ="SELECT FROM orders where ordernumber=$random";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result)>0){
// regenerate random number
}
else{
//insert here
}
?>
can somebody please help me add code to regenerate number if it exists in the db and if the new random number also exists regenerate another one i want to repeat it 5 times just incase. then when its finally made one that doesn't exist i would like the random number to be a variable $ordernumber
thank you very much!!
Re: Check DB, then create random number
Posted: Tue Aug 12, 2014 2:56 pm
by Celauran
Rather than generating a random number, hitting the database to see if it exists, generating another, hitting the database again, could you not use something like UUIDs, which are almost guaranteed to be unique? If not, I'd pull down all values for order number in a single query, store it as an array, and compare your generated randoms against that array.
Re: Check DB, then create random number
Posted: Tue Aug 12, 2014 3:16 pm
by donny
i looked into uuids but theyre pretty long. i just need a 5 digit random number for each order
Re: Check DB, then create random number
Posted: Tue Aug 12, 2014 3:37 pm
by requinix
What are you going to do for the 100,000th order?
Re: Check DB, then create random number
Posted: Tue Aug 12, 2014 4:14 pm
by Celauran
UUIDs are 36 characters, so maybe that's too long for an order number, but surely 5 is too short. What if you used something like a substring of the hash of the current time? Not random as such, but less prone to collisions and a far greater number.
Code: Select all
hexdec(substr(sha1(microtime()), 0, 10));
or something along those lines?
Re: Check DB, then create random number
Posted: Tue Aug 12, 2014 7:52 pm
by donny
that will work fine. thank you very much