Solved

Building on creating unique 5 character strings

Posted on 2012-03-24
4
493 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
4 Comments
 
LVL 110

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 110

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 110

Expert Comment

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

All the best, ~Ray
0

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

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

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this. Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it i…
Introduction Since I wrote the original article about Handling Date and Time in PHP and MySQL several years ago, it seemed like now was a good time to update it for object-oriented PHP.  This article does that, replacing as much as possible the pr…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.

737 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