简体   繁体   English

带while循环的php函数

[英]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... 现在我想有一个while循环来检查$ new_url是否已经存在于我的数据库中...

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. 除了while循环外,我所有工作都可以进行。 and i just cant figure out how to do it... 我只是想不通怎么做...

  • define your code field as UNIQUE in your database 在数据库中将代码字段定义为UNIQUE
  • generate a code and run an INSERT 生成代码并运行INSERT
  • check with mysql_affected_rows() if the INSERT actually happened or not (ie code already present) 使用mysql_affected_rows()检查INSERT是否实际发生(即代码已经存在)

saves you a SELECT query 为您节省一个SELECT查询

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 使用这个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. 请改用uniqid()函数。 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()) . 如果需要更高的安全性(即:不需要相邻的值),只需对输出进行哈希处理: sha1(uniqid())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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