循环直到用 PHP 返回 true

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9459168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:52:02  来源:igfitidea点击:

Loop until returned true with PHP

phploops

提问by DannyF247

I'm generating a random code, and I need to check to be sure that the code isn't already in the database. I'm assuming this requires some type of a loop. I have my query all setup and I need it to run a block of code again if mysql_num_rows == 0.

我正在生成一个随机代码,我需要检查以确保该代码不在数据库中。我假设这需要某种类型的循环。我的查询全部设置完毕,如果mysql_num_rows == 0.

回答by Blender

Use a do...whileloop:

使用do...while循环:

do {
  // Your logic
} while (condition);

回答by James L.

$key = true;

    while($key){
        // Do stuff
        if(mysql_num_rows($result) > 0) $key = false;
    }

回答by Martin Macak

Simple upgrade of James L. script - loop script for test if exist login ID in database. If exist, will add +1 after login:

James L. 脚本的简单升级 - 用于测试数据库中是否存在登录 ID 的循环脚本。如果存在,登录后会加+1:

    $key = true;
    $a = 1;
    $login_test_origin=$login_test;

    while($key){        
    $query_test="SELECT count(*) as 'all'  FROM user WHERE  login='$login_test'";
    $row_test=mysql_fetch_array(mysql_query($query_test));
    $error=$row_test[all];     

            if($error > 0) {
                $key = true;
                $login_test=$login_test_origin.$a;
                $a++;             
                           }

            else { 
                $key = false;
                $login=$login_test;
                 }
        }

echo"Used login ID: $login";

回答by AMB

Here is a quite different route:

这是一条完全不同的路线:

while(true){
    if(/* Your logic which you expect to be true */){
        break;
    }
}