Hello,
can somebody please help me create a random number but it can't exist already in my database.
thank you
Check DB, then create random number
Moderator: General Moderators
Re: Check DB, then create random number
You'll need to be more specific. Start by looking at rand().
Re: Check DB, then create random number
this is what i am working with now
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!!
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
}
?>
thank you very much!!
Re: Check DB, then create random number
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
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
What are you going to do for the 100,000th order?
Re: Check DB, then create random number
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.
or something along those lines?
Code: Select all
hexdec(substr(sha1(microtime()), 0, 10));Re: Check DB, then create random number
that will work fine. thank you very much