Checking if meta_value exists for any user

I'm using gravity forms for a sign-up form and I set up a hidden field that is automatically filled with a random string generated and passed to the form by

add_filter("gform_field_value_random_number", "generate_random_number");
function generate_random_number($value){
   $value =     substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"     ,5)), 0, 7);
 }

This is to use as a unique coupon code/user.This field also appears in their user profile.

Up to here all is well. Where I'm having trouble is checking the database that no user already has that coupon code. At first, I wanted to use get_user_meta, but that only works for one user_id at a time. I need it to check ALL users. So the second thing I thought of was to do a wpdb query somewhat like this:

$wpdb-get_results(
    "
    SELECT meta_value
    FROM $wpdb-usermeta
    WHERE meta_key = 'Referral'
        ")

My final function would basically be the following:

  1. Generate random number and return the variable with it (ex: $value)
  2. Do a while loop to check if $value already exists in the database
  3. End loop when $value does not match anything in the database.

I'm not sure how to make this happen. If anyone can give me a hand or point me in the right direction if this is wrong, it'd be much appreciated! :)

edit: Sorry, here's the site: http://colorplan.ca

Topic user-meta wpdb Wordpress

Category Web


this is working for me

if ( metadata_exists( 'user', $user_id, $meta_key ) ) {
    print_r("Exists");
} else {
    print_r("Not Exists");
}

I personally try to stay away from mysql queries when I can use WordPress functions to achieve the same thing. You could try using get_users, Is this what you are trying to achieve:

<?php
    $blogusers = get_users('meta_value=Referral');
    foreach ($blogusers as $user) {
        echo $user->user_email;
    }
?>

Untested. But that should display every user with a null value for the user meta Refferal. If that works you could change echo $user->user_email;, to update_user_meta($user->id, 'Referral', $coupon_code);

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.