php - Random number insert mySQL not working -


hey created 2 random numbers so:

 $firstlink = intval(mt_rand(100, 999) . mt_rand(100, 999) . mt_rand(1, 9) . mt_rand(100, 999)); // 10 digit  $secondlink = intval(mt_rand(1000, 999) . mt_rand(1, 999) . mt_rand(10, 99) . mt_rand(100, 999)); 

and insert code:

$result = mysql_query("insert useraccount                       (category,fname,lname,firstlink,secondlink,accdate)                        values (  '" . $cat . "',                                 '" . $fname . "',                                 '" . $lname . "',                                 " . $firstlink . ",                                 " . $secondlink . ",                                 '" . date('y-m-d g:i:s',time()). "');"); 

it has no errrs , places data mysql database. however, same number both firstlink , secondlink no matter add database , have no idea why doing it!

the datatype both rows int(15)

you can simplify code , improve randomness of code this:

$firstlink = mt_rand(10000,99999) . mt_rand(10000,99999); $secondlink = mt_rand(10000,99999) . mt_rand(10000,99999);      echo "insert useraccount                       (category,fname,lname,firstlink,secondlink,accdate)                        values (  '" . $cat . "',                                 '" . $fname . "',                                 '" . $lname . "',                                 " . $firstlink . ",                                 " . $secondlink . ",                                 '" . date('y-m-d g:i:s',time()). "');" 

phpfiddle: http://phpfiddle.org/main/code/6nf-wpk

this build random 10-digit code making 2 random 5 digit codes , joining them together. is simpler , easier follow less parts making up. had done 2 mt_rand()s because maximum number possible 2147483647. each mt_rand() function you're using, you're preventing 0 being first digit in section of number, because you're starting first digit @ between 1 , 9.

if don't care first number being 1 or 2 (and never being 3-9 or 0) can use

$firstlink = mt_rand(1000000000,2147483647);  // random 10 digit number $secondlink = mt_rand(1000000000,2147483647); // random 10 digit number 

as general coding tips:

  • be consistent how name variables. have lowercase "l" in "$firstlink" , capital "l" in "$secondlink". php case-sensitive , you'll end using wrong name , getting unexpected (blank) results elsewhere in program.
  • be careful never put user-provided data sql command without protecting against sql injection attacks. use parameterized queries rule. see how can prevent sql injection in php? more details , examples.

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -