如何正确地将值传递给wpdb->Prepare()?

时间:2017-08-18 作者:Luca Reghellin

看这里:

// $term_slugs is a function argument: array(\'foto\', \'video\')

$term_query = "t.slug IN (\'" . implode("\',\'",$term_slugs) . "\') ";

$ids = $wpdb->get_results($wpdb->prepare("
  SELECT
    m.meta_value
  FROM
    " . $wpdb->prefix . "posts p
    INNER JOIN " . $wpdb->prefix . "postmeta m ON m.post_id = p.ID
    INNER JOIN " . $wpdb->prefix . "term_relationships rel ON p.ID = rel.object_id
    INNER JOIN " . $wpdb->prefix . "term_taxonomy tt ON tt.term_taxonomy_id = rel.term_taxonomy_id
    INNER JOIN " . $wpdb->prefix . "terms t ON tt.term_id = t.term_id
  WHERE
    p.post_type = \'%s\'
    AND m.meta_key = \'_thumbnail_id\'
    AND p.post_status = \'publish\'
    AND %s
  ORDER BY RAND()
  LIMIT 1
",
$post_type, $term_query
));
这将写下如下内容:

WHERE
  p.post_type = \'gallery\'
  AND m.meta_key = \'_thumbnail_id\'
  AND p.post_status = \'publish\'
  AND \'t.slug IN (\\\'foto\\\',\\\'video\\\') \'
Shuold be:

WHERE
  p.post_type = \'gallery\'
  AND m.meta_key = \'_thumbnail_id\'
  AND p.post_status = \'publish\'
  AND t.slug IN (\'foto\',\'video\') 
如何操作?

1 个回复
最合适的回答,由SO网友:Luca Reghellin 整理而成

我自己找到了答案。。

(示例代码)

$args_array = array($post_type);
$term_slugs = array(\'foto\', \'video\');

// create a string like \'%s, %s\' ecc
$placeholders = implode(\', \', array_fill(0, count($term_slugs), "%s"));
$term_query = "t.slug IN ($placeholders) ";
$args_array = array_merge($args_array, $term_slugs);

$ids = $wpdb->get_results($wpdb->prepare("
  SELECT
    m.meta_value
  FROM
    " . $wpdb->prefix . "posts p
    INNER JOIN " . $wpdb->prefix . "postmeta m ON m.post_id = p.ID
    INNER JOIN " . $wpdb->prefix . "term_relationships rel ON p.ID = rel.object_id
    INNER JOIN " . $wpdb->prefix . "term_taxonomy tt ON tt.term_taxonomy_id = rel.term_taxonomy_id
    INNER JOIN " . $wpdb->prefix . "terms t ON tt.term_id = t.term_id
  WHERE
    p.post_type = \'%s\'
    AND m.meta_key = \'_thumbnail_id\'
    AND p.post_status = \'publish\'
    AND $term_query
  ORDER BY RAND()
  LIMIT 1
",
$args_array // pass substitutions as an array
));

结束