我正在尝试修改wordpress插件,使其更适合我们的需要。我有一个自定义的user\\u meta,名为practice,我们根据实践来分隔用户,因此我们还需要根据实践来分隔测验结果。我的问题是,我无法让我的查询返回实践。有人能看看这个告诉我我做错了什么吗?
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 );
}
}
}
所有输入都很好,除了没有价值的$practice。
帮助
最合适的回答,由SO网友:Krzysiek Dróżdż 整理而成
我猜meta\\u key不是数字,所以您不应该在SQL查询中使用%d。
$wpdb->prepare( "SELECT meta_value FROM %s WHERE user_id = %d AND meta_key = %s",$userMeta,$user_id,$practiceKey ); // meta_key = %s not %d
另外,您不必以这种方式转义表名。您可以使用
$wpdb->prepare( "SELECT meta_value FROM {$wpdb->usermeta} WHERE user_id = %d AND meta_key = %s", $user_id, $practiceKey );