Jump to content

Update new column in existing table with unique values?


we5inelgr

Recommended Posts

Hi all,

 

I've got an existing table with 1647 rows. I've added a new column that needs to have unique values in it. The values will be created from Upper and lower case letters, as well as numbers. The script I have to do this one time update is this:

 

for ($i=0;$i<1672;$i++) { 
    //generate a 12 digit random alpha-numeric for session id 
    $length=12; 
    $pool=""; 
    // set pool of possible char 
    if($pool == ""){ 
        $pool .= "abcdefghijklmnopqrstuvwxyz"; 
     $pool .= "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
     $pool .= "0123456789"; 
    }// end if 
    mt_srand ((double) microtime() * 1000000); 
    $id = ""; 
    for ($index = 0; $index < $length; $index++) { 
     $id .= substr($pool, (mt_rand()%(strlen($pool))), 1); 
    }//** END nested for loop for $index **// 

$sql = mysql_query ("Update Users Set Unique_ID = '$id'") or exit (mysql_error()); 

 

When I run this, each user gets updated with the same unique ID generated each time through the loop. In the end, all users wind up with the very last $id generated.

 

How can I make this Update Unique so that each time through, the next user in the table gets the next unique $id?

 

There is a field in the table that is unique already.  It's called "Email."

 

Thanks.

A little crude running this in a query loop but I assume this is a one time table update.

<?php
$sql = "SELECT id FROM users";
$result=mysql_query($sql) or die (mysql_error());
while($row=mysql_fetch_array($result)){
	$user_id=$row['id'];

	//generate a 12 digit random alpha-numeric for session id
	$id="";	
	$length=12; 
	$pool=""; 
	// set pool of possible char 
	$pool .= "abcdefghijklmnopqrstuvwxyz"; 
	$pool .= "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
	$pool .= "0123456789";     

	for ($index = 0; $index < $length; $index++) { 
		$id .= substr($pool, (mt_rand()%(strlen($pool))), 1); 
	}//** END nested for loop for $index **// 

$sql = mysql_query ("Update Users Set Unique_ID = '$id' WHERE id = $user_id") or exit (mysql_error());

}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.