Solved

unique random number generation

Posted on 2010-11-21
4
642 Views
Last Modified: 2012-05-10
I'm looking for a php script that generates unique random numbers may be up to 16 digits then insert them in a table.

0
Comment
Question by:a0k0a7
  • 2
4 Comments
 
LVL 1

Accepted Solution

by:
thalueng earned 250 total points
ID: 34185208
Not sure I fully understand your requirement. The following code generates a random number "$rand" and inserts it into table "rand_table" together with an "$id". If the $id already exists in the table, then the previous random number is replaced with the new one. This example works as is for Joomla 1.5, for any other context just replace the last 2 lines of code with your query function.

$rand = mt_rand();
$query =      'INSERT INTO rand_table (id, rand_field)'.
            ' VALUES ('.$id.','.$rand.
            ') ON DUPLICATE KEY UPDATE uid='.$uid.',last_rand='.$rand;
// the following 2 lines are Joomla specific
$this->_db->setQuery($query);
return $this->_db->query();
0
 
LVL 13

Assisted Solution

by:dsmile
dsmile earned 250 total points
ID: 34185234
Here's the script

1. a function to generate 16 digits number uniquely & randomly
2. sample code to insert / select from DB
<?php

/*

* create a random number uniquely base on input

*/

function createNumber($lastNumber) {

	$number = rand(0, 99999999) . rand(0, 99999999);

	while ($number == $lastNumber) {

		$number = rand(0, 99999999) . rand(0, 99999999);

	}



	return $number;

}



session_start();

if (!isset($_SESSION['number'])) {

	$_SESSION['number'] = 0;

}



$number = createNumber($_SESSION['number']);

$_SESSION['number'] = $number;



//init

$host = 'localhost'; $db_user = 'root'; $db_password = '';

$database = 'test';

$connect = mysql_connect ( $host, $db_user, $db_password );

mysql_select_db ( $database );



//insert new number

if ($number) {

	$result = mysql_query("INSERT INTO test_r (number) VALUES ('". $number ."')");

	if (!$result) {

	   echo 'Could not run query: ' . mysql_error();

	   exit;

	}

}



//list generated numbers

$result = mysql_query('SELECT number FROM test_r');

if (!$result) {

   echo 'Could not run query: ' . mysql_error();

   exit;

}



echo 'Generated Numbers: <br />';

while ($row = mysql_fetch_array($result)) {

   echo $row['number'] .'<br />';

}

?>

Open in new window

0
 
LVL 8

Author Comment

by:a0k0a7
ID: 34185568
Thanks a lot for the suggestion really help me figure out a couple things, what I would need to do if I want to check if my random number is in a specific table before making the insert.

If the random number is in the table then I would like to keep generating a random number until the number is not available in the table so i can do the insert.

@Dsmile, @thalueng I appreciate your help.

0
 
LVL 1

Expert Comment

by:thalueng
ID: 34186178
Make rand_field a primary key and change the query to $query = 'INSERT INTO rand_table (rand_field) VALUES ('.$rand.')';

If the value exists in the table, the query will abort with an error. Loop through several mt_rand() and queries until it returns without error.

BTW: use mt_rand(), not rand(), which is faster and better randomizer.
0

Featured Post

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Php pie charts 3 26
phpmailer in WHILE loop - weird results 10 27
A form to still have contents even if some are wrong 10 44
How can I echo a PHP variable in AJAX function? 7 27
Introduction Since I wrote the original article about Handling Date and Time in PHP and MySQL (http://www.experts-exchange.com/articles/201/Handling-Date-and-Time-in-PHP-and-MySQL.html) several years ago, it seemed like now was a good time to updat…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

932 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now