generating random code no duplicates like youtube pages id

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Mr.only
Forum Newbie
Posts: 6
Joined: Mon Dec 27, 2010 6:11 am

generating random code no duplicates like youtube pages id

Post by Mr.only »

i need function to generating random page id with no duplicates in db

something like this

Code: Select all

    function generate_id($length2 = 11)
    {
        $range = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_';
        $max = strlen($range) - 1;

        // Generates random id of length $length.
        $id = '';
        for ($count = 0; $count < $length2; $count++)
        {
            $id .= $range[rand(0, $max)];
        }
        return $id;
    }
and i don't want this check

Code: Select all

    $check = mysqli_query($mysqli, "SELECT ".$table.".token FROM ".$table." WHERE ".$table.".token = '".$random."'");

            if(mysqli_num_rows($check) > 0){

            //ERROR: DUPLICATE TOKEN, CREATE A NEW TOKEN NOW...

            }
some one told me that i can use time function like this

Code: Select all

<?php
    $length1=11;
    function random_text($start,$length1)
    {
        return  substr(md5(time().rand()),$start,$length1);
    }

    $code1=random_text(10,11);
    echo $code1;
    echo"<br />";
    ?>
it works and not needs to make checking in db but the problem is its give me numbers more than letters

and actuality i need use it as pages id and i want it completely like youtube id without duplicate
ex:http://www.youtube.com/watch?v=AxlJV89mFHE

any help .
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: generating random code no duplicates like youtube pages

Post by social_experiment »

Mr.only wrote:but the problem is its give me numbers more than letters
That's not the script's problem so to speak, the md5 hashes the mix you give it and returns a 32-character hexadecimal number. Your first example should (in theory) yield more alphabet-character-containing values because there are 56 characters as opposed to only 10 integers.
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply