?
Solved

randomly generate unique codes in php

Posted on 2009-02-24
14
Medium Priority
?
1,032 Views
Last Modified: 2013-12-12
hi
i want to generate 200 code randomly and insert them into mysql table each code must be unique
CREATE TABLE IF NOT EXISTS `codes` (
  `id` int(10) NOT NULL,
  `randomcode` int(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Open in new window

0
Comment
Question by:mattibutt
  • 5
  • 4
  • 3
  • +2
14 Comments
 
LVL 14

Expert Comment

by:Ionut A. Tudor
ID: 23724392
This is should be pretty unique for only 200 options
<?php
 
for($i=0;$i<200;$i++){
$random = chr(rand(ord('a'),ord('z'))) . rand(1,9999) . chr(rand(ord('a'),ord('z'))) . rand(1,9999) . chr(rand(ord('a'),ord('z'))) . rand(1,9999) . chr(rand(ord('a'),ord('z'))) . rand(1,9999) . chr(rand(ord('a'),ord('z')));
print $random;
 
//mysql insert query
}
 
?>

Open in new window

0
 
LVL 1

Expert Comment

by:flowerbloom
ID: 23724421
Try:

for ($i = 100; $i < 200; &i++) {
  $id = (($i - 100 )+ 1);
  $code = $i . rand(1000,9999);
  $q = "insert into codes (id,randomcode) values ($id,$code);";
  {execute mysql}
}

even if random function comes back with same value, the code prefix changes.
0
 
LVL 1

Expert Comment

by:flowerbloom
ID: 23724435
sorry,
instead of "for ($i = 100; $i < 200; &i++) {" it should have been "for ($i = 100; $i < 300; &i++) {"
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 11

Author Comment

by:mattibutt
ID: 23724481
hi flow
this for line still giving me error
0
 
LVL 14

Expert Comment

by:Ionut A. Tudor
ID: 23724520
mattibutt, my code would be alot usefull when use with more than 10,000 random strings, did you tried it ? And flowerbloom works fine just a simple syntax error it should be $i++ instead of &++
Good luck
0
 
LVL 11

Author Comment

by:mattibutt
ID: 23724549
hi
i have tried it, it didnt work let me try again if i catch any error i get back to you i dont mind generating ten thousands random strings
0
 
LVL 14

Expert Comment

by:Ionut A. Tudor
ID: 23724595
I said with more than 10,000 random but you can control the amount of generated strings in the iteration method in my code `for`, just to clarify
Cheers
0
 
LVL 11

Author Comment

by:mattibutt
ID: 23724678
hi
i have tired to run it but i dont know why its not working
now i am getting the error in the browser.
DB error


<?php
 mysql_connect('localhost','root','pass') or die('could not connect to the database server');
mysql_select_db('testing') or die('could not select database');
mysql_query($sql) or die("DB error");
 
 
 for ($i = 100; $i < 200; $i++) {
  $id = (($i - 100 )+ 1);
  $code = $i . rand(1000,9999);
  $sql =  "insert into codes (id,randomcode) values ($id,$code);";
 
}
 
 
 
?>

Open in new window

0
 
LVL 14

Expert Comment

by:Ionut A. Tudor
ID: 23724724
you should do the mysql_query($sql) or die("DB error"); in the loop, see below code
<?php
 mysql_connect('localhost','root','pass') or die('could not connect to the database server');
mysql_select_db('testing') or die('could not select database');
 
 
 
 for ($i = 0; $i < 200; $i++) {
  $random = chr(rand(ord('a'),ord('z'))) . rand(1,9999) . chr(rand(ord('a'),ord('z'))) . rand(1,9999) . chr(rand(ord('a'),ord('z'))) . rand(1,9999) . chr(rand(ord('a'),ord('z'))) . rand(1,9999) . chr(rand(ord('a'),ord('z')));
  $sql =  "insert into codes (randomcode) values ('$random');";
	mysql_query($sql) or die("DB error:".mysql_error());
}
 
 
 
?>

Open in new window

0
 
LVL 11

Author Comment

by:mattibutt
ID: 23724794
it has only inserted zeros
                    id       randomcode
                  0      0
                  0      0
                  0      0
                  0      0
                  0      0
0
 
LVL 1

Accepted Solution

by:
flowerbloom earned 1000 total points
ID: 23725173
Sorry about the typo up there:

Try:
mysql_connect ('your_db_host_server','your_db_user','your_db_password')
 or die ('Could not connect to the database server.');
mysql_select_db ('your_db')
 or die ('Could not select database.');

for ($i = 100; $i < 300; $i++) {
  $id = (($i - 100 )+ 1);
  $code = $i . rand(1000,9999);
  $q = "insert into codes (id,randomcode) values ($id,$code);";
  mysql_query ($q);
}
0
 
LVL 27

Expert Comment

by:Cornelia Yoder
ID: 23725301
for($i=0;$i<200;$i++){
do{
        $randnumber=rand()%1000000000;
        $result=mysql_query("SELECT * FROM Table where randomcode=$randnumber;");
    }while(mysql_num_rows($result)>0);

mysql_query("INSERT INTO Table VALUES($i,$randnumber);");

}
0
 
LVL 8

Assisted Solution

by:agamal
agamal earned 1000 total points
ID: 23727534
this function will generate unique random code ... and you can specify the lenght


randomPrefix("LENGHT OF CODE")


<?php
function randomPrefix($length)
{
$random= "";
 
srand((double)microtime()*1000000);
 
$data = "AbcDE123IJKLMN67QRSTUVWXYZ";
$data .= "aBCdefghijklmn123opq45rs67tuv89wxyz";
$data .= "0FGH45OP89";
 
for($i = 0; $i < $length; $i++)
{
$random .= substr($data, (rand()%(strlen($data))), 1);
}
 
return $random;
}
 
echo randomPrefix(10); 
 
 ?>

Open in new window

0
 
LVL 11

Author Closing Comment

by:mattibutt
ID: 31550700
thanks guys
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses
Course of the Month17 days, 6 hours left to enroll

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question