Jump to content

[SOLVED] Generate a random string that doesn't exist in DB


Recommended Posts

Hey guys, I'm using the following code to generate a random string:

 

function generatePass ($length)
{

  $password = "";
  $possible = "0123456789bcdfghjkmnpqrstvwxyz"; 
  $i = 0; 
  while ($i < $length) { 
  $char = substr($possible, mt_rand(0, strlen($possible)-1), 1); 
  $password .= $char;
  $i++;

  }

  return $password;
}

 

I need it to check a table though to make sure it doesn't generate one that already exists in my randomID column. Any ideas on how to go about this, having it re-generate the string if it already exists (then checking again, etc)?

You need your DB connection inside the function, than use a while loop, while alreadyExists is true continue, set alreadyExists to false when you know it is not in your DB.

 

Hope that logic helps to get you going.

function generatePass ($length)
{
  $alreadyExists = true;
  while ($alreadyExists) {
    $password = "";
    $possible = "0123456789bcdfghjkmnpqrstvwxyz";
    $i = 0;
    while ($i < $length) {
      $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
      $password .= $char;
      $i++;

    }

     $sql = "SELECT random FROM tbl_name WHERE random = '" . $password . "';
     $res = mysql_query($sql);
     if (mysql_num_rows($res) == 0) {
           $alreadyExists = false;
     }
  }

  return $password;
}

 

Hope that helps. You will have to modify the SQL and make sure you do have a SQL connection for that work.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.