Mysql在900,000之后没有插入所有行

I am trying to insert randomly generated numbers into a mysql table. When i insert 900,000 rows or under, everything is fine. But when I try to insert eg. 1,000,000 only 998,739 rows are inserted. I have tried inserting 999,999 and it also inserts 998,739 rows. I have tried other numbers over 900,000 and none of them inserted the exact amount i wanted to.

I can't find any pattern in the amount of rows it is inserting (like x = x - 900)

If i insert eg. 10 rows after i inserted the 1,000,000 (998,739) rows, there is no problem.

I am inserting the rows like this:

$i = 0;
$length = $_POST['length'];
while($i++ < $length){
    $key = rand(0, $length);
    $codes .= "('$key'), ";
}
    $codes = substr($codes, 0, -2);
    $sql = "INSERT INTO speedtest (Code) VALUES $codes";
    mysqli_query($link, $sql);

?>

Does anyone know what is going on here?

Thanks!

</div>