On my website I automatically generate an 8-digits random number $rndnr via wp_rand() during the registration process and save it as user meta.
How can I check if this number has already been assigned to any user?
I actually handle it with this, while $result reads the value from the database:
$result = $wpdb->get_var("SELECT meta_value from $wpdb->usermeta where meta_key='user_reference_id' AND meta_value = '$rndnr'");
if(empty($result)) return true;
But I don’t know for sure if this code actually would recognize a duplicate?
How would you go about it?
Thank you.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0