Hello everyone i want to make a random number generator and also to check the numbers, and if that number exist in the database than to generate other number... thank you :)

Member Avatar for iamthwee

Pawned from codeigniter:

function random_string($type = 'alnum', $len = 8)
    {
        switch($type)
        {
            case 'basic'    : return mt_rand();
                break;
            case 'alnum'    :
            case 'numeric'  :
            case 'nozero'   :
            case 'alpha'    :

                    switch ($type)
                    {
                        case 'alpha'    :   $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                            break;
                        case 'alnum'    :   $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                            break;
                        case 'numeric'  :   $pool = '0123456789';
                            break;
                        case 'nozero'   :   $pool = '123456789';
                            break;
                    }

                    $str = '';
                    for ($i=0; $i < $len; $i++)
                    {
                        $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
                    }
                    return $str;
                break;
            case 'unique'   :
            case 'md5'      :

                        return md5(uniqid(mt_rand()));
                break;

        }
    }

Usage: random_string('numeric','6');

As for checking if it exists in the db do a select query, if num_rows() returned is >0 you have a conflict albeit unlikely.

<?php

$min = 0;
$max = 100;
$random_number = mt_rand($min, $max);
printf('Your random number is %d', $random_number);
?>

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.