Jump to content

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


katlis

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.

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.