Solved

Building on creating unique 5 character strings

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

[Webinar] How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

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

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
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.

717 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