Using $wpdb prepare and IN argument
-
I have the following code to retrieve a post ID:-
$array = array('5', '9', '15'); $array_count = count($array); $placeholders = array_fill(0, $array_count, '%d'); $placeholders = (array) $placeholders; $placeholder_list = implode(', ', $placeholders); $array_list = implode(', ', $array); $key = 'custom-field-name'; $value = 'custom field value'; $id = $wpdb->get_var( $wpdb->prepare(" SELECT ID FROM {$wpdb->prefix}posts LEFT JOIN {$wpdb->prefix}postmeta ON {$wpdb->prefix}postmeta.post_id={$wpdb->prefix}posts.ID WHERE ID IN ($placeholder_list) AND meta_key = %s AND meta_value = %d ", $array_list, $key, $value ) );
The ID is retrieved correctly but the following error is thrown:-
Notice: wpdb::prepare was called incorrectly. The query does not contain the correct number of placeholders (5) for the number of arguments passed (3). Please see Debugging in WordPress for more information. (This message was added in version 4.8.3.) in /home/xxxxxx/public_html/wp-includes/functions.php on line 5313
Using print_r, I can see that:-
the variable $placeholders is producing Array ( [0] => %d [1] => %d [2] => %d )
the variable $placeholder_list is producing %d, %d, %d
the variable $array_list is producing 5, 9, 15I make the total number of required placeholders to be 5 (3 from the array, the meta key name and the meta key value). The variables for the placeholder list hold the correct number of instances so why is this error being thrown?
Thank you
- The topic ‘Using $wpdb prepare and IN argument’ is closed to new replies.