我有一个包含这些值的数组(包括撇号):
\'course_3202\',\'course_3201\',\'course_3200\',\'course_3199\'
我尝试从Posteta表中的这些值中获取结果。
SELECT * FROM wp_postmeta WHERE meta_key IN (%s) and meta_value=1
我没有得到结果(是的,有数据,我应该得到结果)
RESULT = Array ( )
我的代码如下所示:
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;
}
在phpMyAdmin中,我尝试了同样的方法,并得到了结果(如预期的那样):
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?
最合适的回答,由SO网友:s_ha_dum 整理而成
您需要让替换占位符与数组中的值数量匹配,然后可以将该数组用作prepare
参数。
概念验证:
$a = array(\'course_3202\',\'course_3201\',\'course_3200\',\'course_3199\');
$b = array_fill(0,count($a),\'%s\');
$b = implode(\',\',$b);
$sql = "SELECT * FROM $wpdb->postmeta";
$sql .= " WHERE meta_key IN ({$b}) and meta_value=1";
var_dump($wpdb->prepare($sql,$a));
SO网友:cybmeta
您正在查询postmeta
因此我将使用WP\\u查询类和方法:
$courseids = array( \'course_3202\', \'course_3201\', \'course_3200\', \'course_3199\' );
$meta_query = array();
foreach( $courseids as $courseid ){
$meta_query[] = array(
\'key\' => $courseid,
\'value\' => \'1\',
\'compare\' => \'IN\',
);
}
$args = array(
\'post_type\' => \'post\',
\'meta_query\' => array(
$meta_query
)
);
$query = new WP_Query( $args );
$count_courses = $query->found_posts;