user849137
user849137

Reputation:

generate random number with php and then submit to database

I was wondering how to generate a random 9 digit number with php after a html form submit.

in english:

I have a form on my site....which posts data to a database. I would like to add another function to the php file that will generate a number for every form submit (something like a unique id number for every user that submits the form)

I can do all the database stuff. Just need to know how to generate the number.

Upvotes: 0

Views: 3993

Answers (6)

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

rand() = Max 32768 on windows machines

so if you choose to use:

mt_rand (100000000,999999999);

but i suggest you use the AI id from the database and pad it if your curtain you need length 9

str_pad(mysql_insert_id(), 9, "0", STR_PAD_LEFT);
000000001
000000002
000000003
...
000000199
and so on

Upvotes: 2

Dereleased
Dereleased

Reputation: 10087

I cannot imagine why you would do this instead of using a PRIMARY KEY with AUTO_INCREMENT, but since you ask:

mt_rand() is the way to do.

DO NOT USE rand() -- IT IS SLOW AND FLAWED

For proof of that concept, try the following:

header("Content-type: image/png");
DEFINE('SQUARE_SIZE', 100);
$img = imagecreatetruecolor(SQUARE_SIZE, SQUARE_SIZE);

$ink = imagecolorallocate($img, 255, 255, 255);

for($i = 0, $max = pow(SQUARE_SIZE, 2); $i < $max; $i++) {
    imagesetpixel($img, mt_rand(1,SQUARE_SIZE), mt_rand(1,SQUARE_SIZE), $ink);
}

imagepng($img);
imagedestroy($img);

You'll get pixel noise; if you change the mt_rand calls to rand, it will be a very obvious repeating pattern, and the same pattern every time.

example is adapted from php manual comments for mt_rand()

Upvotes: 0

Raffael
Raffael

Reputation: 20045

Why reinvent the wheel? I recommend you have your database create a unique id via UUID().

Upvotes: 1

Mihai Iorga
Mihai Iorga

Reputation: 39704

you can do database stuff and you cannot generate an id?

random: rand(1, 999999999)

or from that insert i assume mysql: mysql_insert_id() - if you use ID's

Upvotes: 0

Fender
Fender

Reputation: 3055

have a look at the rand function

PHP manual: Rand()

Upvotes: 0

Ryan
Ryan

Reputation: 28187

Try the uniqid function.

See: http://php.net/manual/en/function.uniqid.php

Upvotes: 0

Related Questions