dongpengqin3898 2018-06-28 10:52
浏览 59
已采纳

测试数据库中是否存在数字,如果存在则创建新数据

I have a hurtle I just can't figure out.

I want my code to:

  1. Create a random number
  2. Test if it exist in the database
  3. If it exist, create a new random number og do number 2. again.
  4. If it don't exist, create it in the database.

I've tried the following code, which I found in a similar problem on Stackoverflow, but I just can't figure this out:

$key = true;

while($key){

    $unique_number_new = rand(1000,9999);
    $result = mysql_query("SELECT * FROM brugere WHERE medlemsnummer = $unique_number_new");

    if(mysql_num_rows($result) > 0) {   
        $key = false;   
        // Allready exists

    } else {    
        $key = true;
        // Create in database
    }

        echo "Code done! - " . $unique_number_new;
}

The problem is, it gives me multiple numbers (see https://www.dance4fun.dk/test_folder/number_test.php)

How can I create a code that does the 4 above mentioned, steps?

Hope you can help me out with this!

  • 写回答

1条回答 默认 最新

  • dongnachuang6635 2018-06-28 13:30
    关注

    A reason why your code didnt work:

    • You had 'true' set as the not found result, so if it didnt find anything, it would continue looping.
    • You had the echo showing you the code no matter what.

    This is a way to achieve what you listed out:

    do {
        $unique_num = mt_rand(1000,9999);
        // NOTE: changed mysql_query to use mysqli! (prepared statement not required here)
        $exists = mysqli_fetch_row(
                      mysqli_query(
                          $connection,
                          "SELECT COUNT(*) FROM brugere WHERE medlemsnummer = $unique_num"
                      )
                  )[0];// [0] means grab column result
    } while($exists);
    
    echo "Code done! - " . $unique_num;
    

    This will always run the code once (do), and will repeat if the random number was found in the database. Once it is not found in the database, you then have a random number in a variable to use as your whim after the while loop finishes.

    For these things, its a good idea to add a fail-safe:

    $c = 0;
    do {
       $c++;
       /// other code
    } while ($exists and $c < 1000);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 经gamit解算的cors站数据再经globk网平差得到的坐标做形变分析
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式