0

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 :)

3
Contributors
2
Replies
21
Views
2 Years
Discussion Span
Last Post by harishprakash
0

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.

0
<?php

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.