I have an array containting these values (including the apostrohpes):
'course_3202','course_3201','course_3200','course_3199'
I try to fetch results from these values in postmeta-table.
SELECT * FROM wp_postmeta WHERE meta_key IN (%s) and meta_value=1
I get no result (yes, there is data and I should get results)
RESULT = Array ( )
My code looks like this:
function get_count_courses_array(array $courseids) {
$tmp = array();
foreach($courseids as $cid) {
$tmp[] = "'" . $cid . "'";
}
$courseids = implode(',',$tmp);
global $wpdb;
$sql = "SELECT * FROM $wpdb->postmeta";
$sql .= " WHERE meta_key IN (%s) and meta_value=1";
$result = $wpdb->get_results($wpdb->prepare( $sql, $courseids));
return $result;
}
In phpMyAdmin I tried the same and I do get results (as expected):
SELECT * FROM wp_postmeta WHERE meta_key IN ('course_3202','course_3201','course_3200','course_3199') and meta_value=1
What am I doing wrong?
You need to have your replacement placeholders matching the number of values in your array, and then you can use the array as one of the
prepare
arguments.Proof of concept:
You are querying to
postmeta
table so I would use WP_Query class and methods instead: