0

In a WP plugin that I am creating I have the following SQL:

global $wpdb;
$sql ="SELECT wp_users.`ID`,
        wp_users.`user_email`,
        wp_learndash_user_activity.`activity_id`,
        wp_learndash_user_activity_meta.`activity_meta_key`,
        wp_learndash_user_activity_meta.`activity_meta_value`
        FROM wp_users
        LEFT JOIN wp_learndash_user_activity
         ON wp_learndash_user_activity.`activity_type` = 'quiz'
         AND wp_users.`ID` = wp_learndash_user_activity.`user_id`
        LEFT JOIN wp_learndash_user_activity_meta
         ON wp_learndash_user_activity.`activity_id` = wp_learndash_user_activity_meta.`activity_id`
        WHERE (wp_users.`ID` IN (".implode(',', $idList).")) AND (wp_learndash_user_activity_meta.`activity_meta_key` = 'percentage')";
        
        $result = $wpdb->get_results($sql);

...and have attempted to prepare the statement by converting it to:

        global $wpdb;
        
        $result = $wpdb->get_results($wpdb->prepare("SELECT wp_users.`ID`,
        wp_users.`user_email`,
        wp_learndash_user_activity.`activity_id`,
        wp_learndash_user_activity_meta.`activity_meta_key`,
        wp_learndash_user_activity_meta.`activity_meta_value`
        FROM wp_users
        LEFT JOIN wp_learndash_user_activity
         ON wp_learndash_user_activity.`activity_type` = 'quiz'
         AND wp_users.`ID` = wp_learndash_user_activity.`user_id`
        LEFT JOIN wp_learndash_user_activity_meta
         ON wp_learndash_user_activity.`activity_id` = wp_learndash_user_activity_meta.`activity_id`
        WHERE (wp_users.`ID` IN (".%s.")) AND (wp_learndash_user_activity_meta.`activity_meta_key` = 'percentage')", implode(',', $idList)));
        

But it is no longer working and I expect it is to do with the way I am attempting to pass the implode function as a parameter into %s. How can I correctly pass the result of the implode into %s?

sw123456
  • 3,339
  • 1
  • 24
  • 42
  • Does this answer your question? [pdo prepared statements with wildcards](https://stackoverflow.com/questions/16255657/pdo-prepared-statements-with-wildcards) – kmoser Sep 01 '20 at 06:25
  • What does "not working" mean? What error are you getting? Because it seems you have a massive typo: `"SELECT...".%s."..."` is not a valid expression in PHP. – kmoser Sep 01 '20 at 06:27
  • Meant to post this instead: https://stackoverflow.com/questions/920353/can-i-bind-an-array-to-an-in-condition – kmoser Sep 01 '20 at 06:29
  • FYI: If this plugin is supposed to be used on other sites than just your own, you need to take the table prefix into account. https://codex.wordpress.org/Creating_Tables_with_Plugins#Database_Table_Prefix – CBroe Sep 01 '20 at 07:00

0 Answers0