WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to modify a wordpress plugin to make it more adaptable for our needs. I have a custom user_meta called practice and we separate our users based on practice, so we need to separate quiz results also based on practice. My issue is that I cannot get my query to return the practice. Can someone look at this and tell me what I'm doing wrong?

    function save_score( $json, $user_id = null, $practice = null )
        global $wpdb, $data;
        $db_name = $wpdb->prefix . 'plugin_slickquiz_scores';

        $data    = json_decode( stripcslashes( $json ) );
        $set     = array();
        $now     = date( 'Y-m-d H:i:s' );
        $user_id = $user_id ? $user_id : get_current_user_id();
        $practiceKey = 'user_practice';
       // $practice = $wpdb->get_results( "SELECT meta_value FROM $usrmeta WHERE user_id = $user_id AND meta_key = 'user_practice'" );
       // $usrlevel = $usrlevel ? $usrlevel : $wpdb->get_var( "SELECT meta_value FROM $usrmeta WHERE user_id = '".$user_id."' AND meta_key = user_practice_level" );

        $userMeta = $wpdb->prefix . `usermeta`;
        $sql = $wpdb->prepare( "SELECT meta_value FROM %s WHERE user_id = %d AND meta_key = %d",$userMeta,$user_id,$practiceKey );
        $practice = $wpdb->get_var( $sql );

        $set['name']        = $data->name;
        $set['score']       = $data->score;
        $set['quiz_id']     = $data->quiz_id;
        //$set['createdBy']   = $user_id;
        //$set['createdDate'] = $now;
        $set['usr']         = $user_id;
        $set['usr_practice'] = $practice;

        $wpdb->insert( $db_name, $set );


Everything inputs fine except $practice which does not put a value.


share|improve this question
up vote 0 down vote accepted

I guess meta_key is not a number, so you shouldn't use %d in yous SQL query.

$wpdb->prepare( "SELECT meta_value FROM %s WHERE user_id = %d AND meta_key = %s",$userMeta,$user_id,$practiceKey );  // meta_key = %s not %d

PS. You don't have to escape table name in this way. You can use

$wpdb->prepare( "SELECT meta_value FROM {$wpdb->usermeta} WHERE user_id = %d AND meta_key = %s", $user_id, $practiceKey );
share|improve this answer
THANKS SO MUCH! That was driving me crazy. So %d is for number (digit?) and %s is for string I'll remember that. – richbai90 Jun 19 '13 at 15:30
In fact, you can't escape the table name in that way. You will end up with quotes around the table name and end up with a MySQL error. – s_ha_dum Jun 19 '13 at 16:25

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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