2

I have made a random character generator, but how can I check if an result already exist in the database?
E.g., if I want 5000 results, and 1 result is equal to an result in the database, it must create a new result in the for-loop.

$previous = array();

for ($i=1; $i<=$quantity; $i++){
                       
    $unique_found = false;
    while(!$unique_found){
        $a = substr(str_shuffle("1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 4);
        $b = substr(str_shuffle("1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 4);
        $c = substr(str_shuffle("1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 4);
        $d = substr(str_shuffle("1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 4);

        $code = "$a-$b-$c-$d";

        if(!in_array($code,$previous)){
            $unique_found = true;
            $previous[] = $code;
            echo .$code .'<br>';
        }
    }

}

2
  • what problem you are facing in above code?? Commented Mar 10, 2015 at 9:23
  • You can check into database but what if your data is too much ? I like to suggest Timestamp(); of php which will provide you unique key every time. Commented Mar 10, 2015 at 9:26

1 Answer 1

1

Populate the $previous array with results in the database already.

$previous = array();
$sql = "SELECT `code` FROM `table`";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
    $previous[] = $row['code'];
}

for ($i=1; $i<=$aantal; $i++){
    // ....
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.