Trying to check a user entered value against one stored in database; always returns error?

I’m working on a sort-of registration system for a WordPress site. The bulk of the work is done with the “Formidable Forms Pro” WP plugin.

In the system a code is generated for each player that has been ‘accepted’. The player is then sent an email with the code and is expected to enter it in a field on another form.

Read More

I would post this question on the Formidable support form but… they don’t help with custom code.

Basically, the issue is that no matter what code is entered in the field the error message is ALWAYS returned, even if the code is in fact in the database. I’m not sure what I’ve done wrong – and am unsure of how I can debug this in WordPress. I have checked that my field values (stored as globals for the time being) are correct and they are.

Anyways, here’s the php function in question:

add_filter('frm_validate_field_entry', 'validatePlayerPassCode', 10, 3);
function validatePlayerPassCode($errors, $posted_field, $posted_value)
{
    global $wpdb;
    global $code_entry_field;
    global $code_field;

    if ($posted_field->id == $code_entry_field) {
        $prefix = $wpdb->prefix;

        $actual_codes = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT meta_value FROM %s WHERE field_id = %d",
                $prefix . "frm_item_metas",
                $code_field
            ));

        if (in_array($posted_value, $actual_codes)) {
            return;
        }

        $errors['field'. $posted_field->id] = '<p>Failed to register player, player passcode incorrect.</p>';
    }

    return $errors;
}

To sum up, what is wrong in this code of mine that causes correct codes to still be read as wrong?

Thanks!

Related posts

Leave a Reply

1 comment

  1. Your array is not what you think it is:

    $actual_codes = $wpdb->get_results(...);
    

    Will get you (from the WordPress codex):

    Generic, multiple row results can be pulled from the database with
    get_results.

    So your $actual_codes array is a multi-dimensional array where each row contains an array with the results from the database: You have an array of arrays and not an array of values. In your case these arrays contain just one element, but that element is not a direct value of the $actual_codes so this will always fail:

    if (in_array($posted_value, $actual_codes)) {
    

    Instead of selecting all the codes in your database and trying to match your code with the results, you should select just that row from the database that has that code and see if your query returns 0 or 1 rows.