Jump to content

PHP - Generating unique number for database field


spaceman12

Recommended Posts

Hey guys,

I m not yet an experienced coder. SO faced alot of problems. Here, I'm trying to generate a UNIQUE RANDOM NUMBER set between two numbers. Repetative occurance must be avoided by all means as I want every number so generated bears a unique value. In other words, every values that made entry into the field of my database should be differant from each others.

 

 

<?php
$conN=mysql_connect("localhost","root","");
if(!$conN)
{
die('error'.mysql_error());
}
mysql_select_db("freebie_allusers",$conN);
$UIN=mt_rand(1,5);
$locateUIN="SELECT UIN FROM user_info WHERE UIN='".$UIN."'";
$fetchUIN=mysql_query($locateUIN);
$resultUIN=mysql_num_rows($fetchUIN);
if($resultUIN>0)
{



WHAT CODE IS REQUIRED HERE SO AS TO GENERATE UNIQUE RANDOM NUMBER?






}

else 
echo $UIN;
?>

 

Thanx in advance

Link to comment
Share on other sites

use rand().

 

<?php $random_number = rand(); ?>

 

To be specific about the number length, read the manual entry for rand on php.net.

 

What a lot of people do is create an id field and set it as a primary key with auto increment enabled. That way you don't even have to mess with the id. But you have stated you don't want repetition. The reason a lot of others do this is because with rand you always have the slight possibility of trying to insert a number you have already used. Especially if your using a primary key.

Link to comment
Share on other sites

Those generated numbers will serve as a primary Identification code for all users and it should be auto generated by the server itslef.  All the number so generated will bear a modulo of some number  which i can set it later on but what i'm trying to do at this stage is to abstain the events of recording the same value of number in the database field.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.