Solved

Building on creating unique 5 character strings

Posted on 2012-03-24
4
489 Views
Last Modified: 2012-03-24
Hi,
Below is some code generously contributed by one of the fellows on the site. If you were to run it, it generates ( as per my settings below) 2500 unique 5 character strings.
I'm trying to adjust the code below slightly so that I can add the random strings into an already existing database table into a column for arguments sake called: access

I have an ongoing need to be able to add a column of unique strings (access codes in my case) to tables that already exist.

So in a perfect world I would simply check how many rows my table is (or perhaps the revised code could check the amount of rows), or enter the number ie: 2501 for example and it would insert the values into the column specified.

Can anyone adjust to do that? I'm struggling as a newbie to get it to work properly.

<?php // RAY_random_unique_string.php
error_reporting(E_ALL);
echo "<pre>\n";



// GENERATE A SHORT UNIQUE RANDOM STRING FOR USE AS SOME KIND OF KEY
// NOTE THAT THE DATA BASE MUST HAVE THE rand_key FIELD DEFINED AS "UNIQUE"
// NOTE THAT THE LENGTH ARGUMENT MUST MATCH THROUGHOUT
define('ARG_LENGTH', 5);



// CONNECTION AND SELECTION VARIABLES FOR THE DATABASE
$db_host = "localhost"; // PROBABLY 'localhost' IS OK
$db_user = "";
$db_word = "";
$db_name = "";

// LIVE DATABASE CREDENTIALS
//


// OPEN A CONNECTION TO THE DATA BASE SERVER
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-connect.php
if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB CONNECTION: ";
    echo "<br/> $errmsg <br/>";
}

// SELECT THE MYSQL DATA BASE
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-select-db.php
if (!$db_sel = mysql_select_db($db_name, $db_connection))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB SELECTION: ";
    echo "<br/> $errmsg <br/>";
    die('NO DATA BASE');
}
// IF WE GOT THIS FAR WE CAN DO QUERIES




// FUNCTION TO CREATE A DATABASE TABLE
function create_myTable()
{
    $length = ARG_LENGTH;

    mysql_query("DROP TABLE IF EXISTS myTable");
    $psql  = "CREATE TEMPORARY TABLE myTable ( ";
    $psql .= "_key        INT(8)            NOT NULL AUTO_INCREMENT, ";
    $psql .= "rand_key    VARCHAR($length)  UNIQUE NOT NULL DEFAULT '?', ";
    $psql .= "other_data  VARCHAR(128)      NOT NULL, "; // AS NEEDED BY YOUR APPLICATION
    $psql .= "PRIMARY KEY(`_key`) ";
    $psql .= " ) ENGINE=INNODB DEFAULT CHARSET=ascii";
    if (!$p = mysql_query($psql)) { die( mysql_error() ); }
}




// FUNCTION TO MAKE A RANDOM STRING
function random_string()
{
    // POSSIBLE COMBINATIONS = pow($length,strlen($chr)); = 4.6E18 IF LENGTH IS 4
    //     1...5...10...15...20...25...30......
   $chr = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
   $str    = "";
   while(strlen($str) < ARG_LENGTH)
   {
       $str .= substr($chr, mt_rand(0,(strlen($chr))), 1);
   }
   return($str);
}




// FUNCTION TO ENSURE THE RANDOM STRING IS UNIQUE
function make_random_key()
{
    $rand_key = '';
    while ($rand_key == '') // GENERATE A UNIQUE AND RANDOM TOKEN
    {
        $rand_key = random_string(ARG_LENGTH);
        $isql     = "INSERT INTO myTable ( rand_key ) VALUES ( '$rand_key' )";
        if (!$i   = mysql_query($isql)) // IF QUERY ERROR
        {
            $err   = mysql_errno();
            if ($err == 1062) // DUPLICATE UNIQUE FIELD ON rand_key
            {
                $rand_key = '';
            }
            else
            {
                /* HANDLE FATAL QUERY ERROR ($isql) */
            }
        }
    }
    return $rand_key;
}




// SHOW HOW TO MAKE LOTS OF UNIQUE AND RANDOM STRINGS
create_myTable();

$kount = 0;
$array = array();
while ($kount < 2501)
{
    $array[] = make_random_key();
    $kount++;
}

print_r($array);
                                            

Open in new window

0
Comment
Question by:tjyoung
  • 3
4 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 37760606
This script already adds the random strings to a data base table.  See line 90.  

You can use ALTER TABLE to add a column to an existing table.  Then change the INSERT statement on line 89 to point to the altered table and use the appropriate column names.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 37760611
If you want to post the CREATE TABLE statements for your existing tables (before ALTER TABLE) I may be able to help you with a code sample.
0
 
LVL 1

Author Closing Comment

by:tjyoung
ID: 37760653
Sometimes you just have to hear it from someone else. Adjust the table rand_key and dropped the values right into the table perfectly.
thanks sorry for the trouble.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 37760666
No trouble at all - glad to turn on the lightswitch ;-)

All the best, ~Ray
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
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.

707 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

18 Experts available now in Live!

Get 1:1 Help Now