How to check if a meta value has already been assigned to any user?

Here is an approach you could take to do this. It’s problematic if you have a large number of users, but it could be adapted in-time.


do {
    // 1. generate your unique random number
    $result = rand();

    // 2. check it is really unique
    $is_unique = count( get_users( array(
            'meta_key'   => 'user_reference_id',
            'meta_value' => $result,
        ) ) ) === 0;

} while ( !$is_unique );

// 3. Store user meta $result
update_user_meta( $user_id, 'user_reference_id', $result );

Assumptions:

  • I’ve used rand() but frankly you should be using something like UUIDs and this way you wouldn’t need a loop like this to check for whether your number is unique. But I’ve provided this approach as it’s likely going to solve for your problem in the way you’ve designed it currently.
  • there is no handling here for WPMS or other such mods.

Edit:

Your original question keeps changing, so I’ll leave this edit as the last change.

Following your comments, I’m providing code so that you can create a Unique ID every time using UUIDs. Instead of the loop to ensure your custom random codes are unique, UUIDs ensure codes are unique by design.

So simply:

// 1. Generate the random ID
$rndnr = wp_generate_uuid4();

// 2. Store the ID
update_user_meta( $user_id, 'user_reference_id', $rndnr );

// 3. Get the user meta key in the future, simply:
get_user_meta( $user_id, 'user_reference_id' );

Assumptions:

  • WordPress is at least version 4.7

In your original question you didn’t state that you were using 8-digit codes. Not sure why you picked 8, but if you update your system to use UUIDs you solve your issues of uniqueness.

I’m also using update_user_meta and get_user_meta – it’s unclear why you’re using MySQL select statements when these helper functions are available.