Solved

Building on creating unique 5 character strings

Posted on 2012-03-24
4
492 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 109

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 109

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 109

Expert Comment

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

All the best, ~Ray
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Does the idea of dealing with bits scare or confuse you? Does it seem like a waste of time in an age where we all have terabytes of storage? If so, you're missing out on one of the core tools in every professional programmer's toolbox. Learn how to …
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
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 create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

820 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