预准备语句的WPDB占位符和第二个参数

时间:2016-05-01 作者:Wordica

如何为这种sql prepare设置占位符和第二个参数

$wpdb->prepare(
    "SELECT ID 
     FROM {$wpdb->posts} 
     WHERE post_type = \'attachment\' AND ID IN (\'".implode("\',\'",$slideshow_imgs)."\') 
     ORDER BY menu_order ASC"
);
答案??

我这样做,没有调试错误:

$str = \'attachment\';

$ids_img = implode("\',\'",$slideshow_imgs);

 $images = $wpdb->get_col($wpdb->prepare("SELECT ID FROM {$wpdb->posts} 
WHERE post_type = %s AND ID IN (%d) ORDER BY menu_order ASC",$str,$ids_img));

2 个回复
SO网友:kaiser

仅使用%s 对于字符串和%d 用于数字替换。不要忘记使用合适的esc_*() 函数(使用全文搜索esc_function reference).

global $wpdb;
$wpdb->show_errors = true;
$wpdb->suppress_errors = false;
! defined( \'DIEONDBERROR\' ) and define( \'DIEONDBERROR\', true );

$sql = <<<SQL
SELECT ID 
FROM {$wpdb->posts} 
    WHERE post_type = \'attachment\' 
    AND ID IN (%s) 
    ORDER BY menu_order 
    ASC
SQL;

# Make sure to `esc_*()` the arguments properly!
$statement = $wpdb->prepare( $sql, implode( "\',\'", $slideshow_imgs ) );
# Example: Query … there are other methods as well:
$wpdb->query( $statement );
# DUMP the result and any possible errors
var_dump( $wpdb->last_query, $wpdb->last_error );

SO网友:birgire

替代手动编写SQL查询的另一种方法是使用,例如:

$post_ids = get_posts( 
    [
        \'fields\'    => \'ids\',
        \'post_type\' => \'attachments\',
        \'orderby\'   => \'menu_order\',
        \'order\'     => \'ASC\',
        \'post__in\'  => wp_parse_id_list( $input_ids )
    ]
);
handy在哪里wp_parse_id_list() 核心功能用于:

清理以数组、逗号或空格分隔的ID列表。

这将生成以下SQL查询:

SELECT wp_posts.ID 
FROM wp_posts 
WHERE 1=1 
    AND wp_posts.ID IN (1,2,3) 
    AND wp_posts.post_type = \'attachments\' 
    AND (wp_posts.post_status = \'publish\') 
ORDER BY wp_posts.menu_order ASC 
LIMIT 0, 5
如果$input_ids = [1,2,3].

但实际上this is how 这个post__in 输入已在中清理WP_Query:

$post__in = implode(\',\', array_map( \'absint\', $q[\'post__in\'] ));
$where .= " AND {$wpdb->posts}.ID IN ($post__in)";
附言:我现在记得贴了张票#34525 建议使用wp_parse_id_list() 在内部WP_Query ;-)