Generate Random Number and Check for Duplicates

I’m trying to generate a random 5 digit number for each Wordpress user when they log into their profile. I have learned how to generate the number. This number must be unique for each user/member and I can not get the code to check for duplicates.

/*
Gate Code
* Gate Codes are generated when users are registered or when the membership account page is accessed for the first time.
*/
//Generate gate_code when a user is registered.
function generate_gate_code($user_id)
{
$gate_code = get_user_meta($user_id, "gate_code", true);
//if no gate code, create one
if(empty($gate_code))
{
global $wpdb;
//this code generates a random 5 digit number from the time
while(empty($gate_code))
{
$gate_code = rand(0,64999);
$gate_code = str_pad($gate_code, 5, '0', STR_PAD_LEFT);

$check = $wpdb->get_var("SELECT meta_value FROM $wpdb->usermeta WHERE meta_value = '" . esc_sql($gate_code) . "' LIMIT 1");
if($check || is_numeric($gate_code))
$gate_code = NULL;
}
//save to user meta
update_user_meta($user_id, "gate_code", $gate_code);
return $gate_code;
}
}
add_action('user_register', 'generate_gate_code');

What is the purpose of the random number?

Members will use this random number as a passcode/pin to enter club facilities. The gate system requires a five digit number and allows the members to enter numbers on a keypad to unlock the gate.

This gate code will show on the membership card and in their profile. I have that part working fine. The only piece I’m missing is the check for duplicates when the number is created.

If I remove the $check variable and all code down to the //save to user meta, it works fine.

So, one issue I see is the if functionality.

if($check || is_numeric($gate_code))

The first should be false if the code doesn’t exists, but the check to see if the code is numeric should always be true. Which would translate to a null every time. And, because you are building the string and know what it is being created from, the check isn’t needed anyway.

Sponsor our Newsletter | Privacy Policy | Terms of Service