1

I am working on coding a PHP form for my website that requires the user to enter a code before the form becomes active. I have a field called "used" that I set up as a Boolean/TinyInt which I thought would return 0, 1 or 'null' but it doesn't seem to be working like that.

Currently I have 2 entries in this database, one of them has a 1 in the 'used' field and the other has nothing(null) but for some reason, both of those queries return "1."

All of the codes will be entered in the database with 'null' assigned to the "used" field by default. When they enter their code, it first checks to see if that code exists in the database, if it does, then it checks the 'used' field to see if someone has already registered using that code.

I am quite new to WP queries, so could anyone let me know what the best way to accomplish this would be? Here is my code so far:

$enteredCode = $_GET['code'];

global $wpdb;

$codeQuery = $wpdb->query("SELECT used FROM rpp_codes WHERE code='".$enteredCode."'");
$exists = $wpdb->get_results("SELECT used FROM rpp_codes WHERE code='".$enteredCode."'");

if (count ($exists) < 1) {
    echo "invalid";
} else {
    if ($codeQuery == 1) {
        echo "true";
    } else {
        echo "false";
    }
}
  • 1
    $wpdb->get_results() returns an index array of row objects, but it looks like you're expecting $exists to contain the actual value of the used column. you probably want $wpdb->get_var(): codex.wordpress.org/Class_Reference/wpdb#SELECT_a_Variable – karpstrucking Sep 16 '14 at 14:56
  • Perfect, that is exactly what I needed, please post this as the answer and I will accept. Thanks again! – user13286 Sep 16 '14 at 15:13
  • glad to help :) – karpstrucking Sep 16 '14 at 15:32
2

$wpdb->get_results() returns an index array of row objects, but it looks like you're expecting $exists to contain the actual value of the used column. you probably want $wpdb->get_var(): http://codex.wordpress.org/Class_Reference/wpdb#SELECT_a_Variable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.