Case
Case

Reputation: 281

generate Unique ID sequence

I want to generate a 7 number Unique ID this is my function to generate.

function generate_guid($length){
    $alphabet = '1234567890';
    $tip = array();
    $alphaLength = strlen($alphabet) - 1;
    for ($i = 0; $i < $length; $i ++) {
        $n = rand(0, $alphaLength);
        $tip[] = $alphabet[$n];
    }
    return implode($tip);
}

Now this is my register function

function create_user($email, $name, $country, $password){

    $ipaddress = $_SERVER['REMOTE_ADDR'];    

    $guid = generate_guid(7);

    $active = 0;

    if (email_exists($email)) {
        return false;
    } else 
        if (name_exists($name)) {
            return false;
        } else {

            $hashed_password = password_hash($password, PASSWORD_BCRYPT);

            $db = dbconnect();

            //MyQuery Code//

            $stmt->close();            

            return true;
        }
}

Now I am able to generate and I am able to check if user name and email exist. my issue is how can I check if the guid exist without error and generate new to insert into db ? Or if some one has a better suggestion. the main thing I am trying to accomplish is must be 7 no more lengths long all numbers.

I read about unique ID but it says its not guaranteed, also it has letters. is there a better approach?

I came across this but is aspx how to generate unique id per user? would it be possible to generate my function in sequence?

Upvotes: 0

Views: 3189

Answers (2)

Bhaskar Jain
Bhaskar Jain

Reputation: 1691

Try this:

function generate_guid($length){
    $alphabet = '1234567890';
    $tip = array();
    do{
        $uniqueId = substr(str_suffel($alphabet), 0, $length );
        //check uniquekey in database like you check unique username
        //something like that
        $sql = 'select * from tablename where uniqueId = "'.$uniqueId.'"';//if your using PDO, bind accordingly
        $result = mysqli_query($conn, $sql);
    }while(mysqli_num_rows($result)); //if no rows, loop will break and you would get uniqu id in $uniqueId variable
return $uniqueId;
}

Upvotes: 1

Indra
Indra

Reputation: 436

you can try this to generate unique from int with PHP https://gist.github.com/Sommerregen/78e5ea478aacfd382323

when hash the number then change $len to 7 you can hash microtime or other incremental number to make sure it is unique.

Upvotes: 1

Related Questions