简体   繁体   中英

php function with a while-loop

I have a function that generates a random combination.

my function looks like this:

  function random_gen($length) {
  $random= "";
  srand((double)microtime()*1000000);
  $char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  $char_list .= "abcdefghijklmnopqrstuvwxyz";
  $char_list .= "1234567890";
  // Add the special characters to $char_list if needed

  for($i = 0; $i < $length; $i++)
  {
    $random .= substr($char_list,(rand()%(strlen($char_list))), 1);
  }
  return $random;
}

$new_url = random_gen(6);

Now i would like to have a while-loop that checks if $new_url already exist in my database...

And then insert the result like this:

mysql_query("INSERT INTO lank (url, code) VALUES ('$url', '$new_url')"); 

I got everything to work except the while-loop. and i just cant figure out how to do it...

  • define your code field as UNIQUE in your database
  • generate a code and run an INSERT
  • check with mysql_affected_rows() if the INSERT actually happened or not (ie code already present)

saves you a SELECT query

while ( true ) {
    $new_url = random_gen(6);
    mysql_query("INSERT INTO lank (url, code) VALUES ('$url', '$new_url')");
    if ( mysql_affected_rows() )
        break;
}

Use this random_generator

function random_gen($length) {
  $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

  $string = '';
  for ($i = 0; $i < $length; $i++) {
    $string .= $characters[rand(0, strlen($characters) - 1];
  }
  return $string;
}

您不需要while循环,只需执行查询

mysql_query("SELECT COUNT(*) FROM lank WHERE code = {$new_url}");

It's pretty straight forward:

$sql = "SELECT COUNT(*) as num FROM lank WHERE code='{$new_url}'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);

while($row['num'] > 0) {
    $new_url = random_gen(6);

    $sql = "SELECT COUNT(*) as num FROM lank WHERE code='{$new_url}'";
    $result = mysql_query($sql);
    $row = mysql_fetch_assoc($result);
}

This should work, without repeating code:

while(true) {
    $new_url = random_gen(6);

    $sql = "SELECT COUNT(*) FROM lank WHERE code='{$new_url}'";
    $result = mysql_query($sql);
    $row = mysql_fetch_row($result);
    if (!$row[0])
        break;
}

Use the uniqid() function instead. It will always generate a random result.

If you need more security (ie: you don't want adjacent values), simply hash the output: sha1(uniqid()) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM