防止在PHP中创建重复的条目

I want to randomly create a number of an user id, but it shouldn't be repeated/duplicated.

I wanted to ask if there is a good approach in general if my aim is to INSERT it into in a MySQL database? I don't want to create a new user. Its for another table.

I want to insert random data with random user id's to create test-comment entries users have made, but not I want to display different users. That's why I need it. It's not about autoincrementing with primary key in the main user table. I want to fill out a comment section

Example:

user_id: 54,34,30 randomy generated with PHP (mt_rand() function). Now I have about 1000 users I want to randomize, but there's still a chance it could be repeated at some point. So let's say now these are the values: 54,54,32

This means it will insert a same user twiche in further steps, where I INSERT this user id in the comment table. So I just need another number randomly generated if it's already has been generated.

The best approach would be to create a GUID, rather than an integer. PHP has built-in methods to create these unique codes.

If you are inserting into a database, I would think that the most robust approach would be to create a primary key, and insert your entries one at a time. Since the DB call will error if you try to insert a duplicate ID, that's an appropriate place to check for an error and choose a different ID if you need to - although if you use a GUID, the chances of duplication are already negligible.

EDIT:

So if I understand what you are trying to do correctly, you want to create an array of random arrays of user ids, which are integers between 1-1000, where no two ids are repeated.

I am assuming that performances is not a big issue, since this sounds like test/dummy data. So the simplest way, in my opinion, would be to avoid having to test for an existing id on each id creation, and just shuffle your array.

So, you start with an array of 1000 ids, and then you loop through x number of times, shuffle the array, and slice off a random number of ids from the beginning of the array. Here is some code I have tested. It outputs what I think you want to create.

$ids = array();
$commentIds = array();
$numIds = 1000;
$numComments = 10;
for($i=0; $i<$numIds; $i++)
{
    $ids[$i] = $i;
}
for($s=0; $s<$numComments; $s++)
{
    shuffle($ids);
    $num = mt_rand(1,10);
    echo("rand:$num");
    $commentIds[$s] = array_slice($ids,0,$num);
    print_r($commentIds[$s]);
}

Is that what you mean?

If you have a specific number of users you want to add in, try just incrementing a digit and using that as the username. That way, they're all unique, and you don't have to force kill it after 30 seconds. This should be the easiest way of doing it, unless you need actually random (non-sequential) ids.