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.
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
Why reinvent the wheel? I recommend you have your database create a unique id via UUID().
Try the uniqid
function.
See: http://php.net/manual/en/function.uniqid.php
have a look at the rand function
PHP manual: Rand()
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
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.
精彩评论