while-loop工作不正常

I want to create a page, where I can create Keys, and save them in a databank, but I got some problems.

There is a textfield, where you can write in, how many keys you want to create. For example I write 5 in, but it does only 3 entrys in the databank, but down in the code is an echo command, which says that he did it 5 times, here is a screenshot:

enter image description here

Also, what I noticed is, that the website is doing max 3 entrys in the databank, for example I write 10, and he still only does 3 entrys.
If I write only 1-3 keys, the while-loop is working.

echo "<p><a href='key.php'>Betakey administration</a></p>";

echo "<form action='#' method='POST'>";
echo "<input type='number' name='numberkeys' placeholder='Number of Keys'>";
echo "<br>";
echo "<input type='submit' name='createkey' value='Create Key'>";
echo "<input type='submit' name='keyanzeigen' value='Show all Keys'>";
echo "<input type='submit' name='unusedkeys' value='Show all unused Keys'>";
echo "<input type='submit' name='usedkeys' value='Show all used Keys'>";
echo "</form>";

$createdkeys=0;

if(isset($_POST['createkey'])){


  $minus= array(5,10,15);

  while($createdkeys<$_POST['numberkeys']){

  //creation of the keys
  for($i=1;$i<20 ;$i++){

    if(in_array($i,$minus)){
      $key=$key."-";
    }
    else{       
      $key=$key.mt_rand(0,9);
    }

    //the key looks like this: 1234-5678-1234-5678

  }


  //here it checks, if the key already exists
  $check = mysqli_query($db,"SELECT keyy FROM keyys WHERE keyy='$key'");
  $check = mysqli_fetch_array($check);

  //if the code not exists, the website will insert the key in the databank  
  //the website will echo the variable $createdkeys and increase the variable $createdkeys by one
  if(!isset($check)){
    $createdkeys= $createdkeys+1;
    echo "<p>".$createdkeys."</p>";
    mysqli_query($db,"INSERT INTO keyys VALUES('$key','NO')"); 
  }

  }
}