php,控制生成时复制名称

i'm new in php. i just want to generate random names (or what you want...). it does works! but when i put in the middle of the code one "do/while" to control and avoid duplicates names it DOES NOT WORKS.... why? what's wrog with my code? i'm exhauste, destroyed.

<?php
require_once 'config.php';
require_once 'dbconn.php';

function getnome() {
    $nome = ['tin', 'pin', 'nid', 'din', 'vin'];

    return $nome[mt_rand(0, count($nome) - 1)];
}

for ($f =0; $f<6; $f++) {
    $arr = [];
    do {
    $x = getnome();
       }
    while (in_array($x, $arr));
    $arr[]=$x;

    $query = "INSERT INTO ants (ant_id, nome) VALUES (NULL, '".getnome()."')";
        $res = $mysqli->query($query);
        if (!$res) {
            echo('<br>Error' . $mysqli->error);
        } else {
            echo $mysqli->affected_rows . ' created';
        }

}
?>

enter image description here

A simpler way to get unique values out of an array is to randomize the array and then process it in order.

$stmt = $mysqli->prepare("INSERT INTO ants (nome) VALUES (?)");
$stmt->bind_param("s", $a_nome);
$nome = ['tin', 'pin', 'nid', 'din', 'vin'];
shuffle($nome);
foreach ($nome as $a_nome) {
    $stmt->execute();
}

There are two main problems:

  1. You're reinitializing $arr with each iteration of the for loop, so it isn't actually keeping track of the random values you've already inserted. You need to initialize it before the for loop.

  2. You're not using the non-duplicate value of $x you just got in the do... while loop in your insert statement. You're calling the getnome function again, which will give you another (possibly duplicate) value. You need to use $x instead.


$arr = [];                      // initialize $arr here instead
for ($f = 0; $f < 6; $f++) {
    do {
        $x = getnome();
    }
    while (in_array($x, $arr));
    $arr[] = $x;

    // use $x instead of getnome()    
    $query = "INSERT INTO ants (ant_id, nome) VALUES (NULL, '" . $x . "')";
    $res = $mysqli->query($query);
    if (!$res) {
        echo('<br>Error' . $mysqli->error);
    } else {
        echo $mysqli->affected_rows . ' created';
    }

}

Another problem you'll encounter once you've fixed the other two things is that you're trying to insert six unique values, but your getnome function can produce only five, so it looks like the do...while loop will become infinite on the last attempt. (That may just be something that got lost in translation when you created your example, but it is a possibility with while or do...while loops that you need to be careful about.)