如何在WordPress中正确使用IN数组?

时间:2014-03-19 作者:bestprogrammerintheworld

我有一个包含这些值的数组(包括撇号):

\'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?

2 个回复
最合适的回答,由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;

结束

相关推荐

$wpdb in php 5.5

我正在帮助一位朋友更新他们的网站,并将其移动到新的服务器上。他们的旧服务器运行php 5.3.6-13,新站点运行php 5.5。有一个使用$wpdb的自定义插件,允许用户编辑写入数据库中自定义表的一些信息,特别是:$query = \"UPDATE wp_building_plan SET sale_price = \'$sale_price\', available = \'$available\', broker_name = \'$broker_name\', broker_email = \'$