将逗号分隔列表传递给自定义wordpress查询

时间:2010-07-14 21:44:45

标签: php sql wordpress

好的,这就是发生了什么...

我正在从Google Analytics中提取最受欢迎的帖子列表,我将它们放在一个数组中

$thisnumber = 0;

$start = date('Y-m-d', (time() - (60 * 60 * 24 * 30)));
$end = date('Y-m-d');
$limit = $getnumber;
$titles = array();

$login = new GADWidgetData();
$ga = new GALib($login->auth_token, $login->account_id, 60);
$pages = $ga->pages_for_date_period($start, $end);

foreach($pages as $page) :
    $title = $page['children']['value'];
    $titlearray = explode(' |', $title, -1);
    $titlesub = implode( "", $titlearray);
    $thetitles[] = $titlesub;
    $thisnumber++;
    if($thisnumber > ($getnumber*2)) break;
endforeach;

$titles_list = implode( ",", $thetitles);

所以在这之后,我留下了$ thetitles中的一系列标题和$ titles_list中存储的标题列表

现在我需要将所有这些标题发送到一个完整的wordpress查询 - 所以我有一个函数:

function get_post_by_title($page_title, $output = OBJECT) {
global $wpdb;
    $post = $wpdb->get_var( $wpdb->prepare( "
    SELECT wposts.* 
    FROM $wpdb->posts wposts
    WHERE post_title = %s 
    AND post_type='post'
    AND post_status = 'publish'", $page_title ));

    if ( $post )
        return get_post($post, $output);

return null;

}

不幸的是,这可能是一堆查询,而在一个旅行严重的网站上,这可能会让事情陷入困境。我试图使用SQL IN函数,但我认为我做错了

$querystr = "
SELECT wposts.* 
FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
WHERE post_title IN ($titles_list) 
AND wposts.post_status = 'publish' 
AND wposts.post_type = 'post'";

$pageposts = $wpdb->get_results($querystr, OBJECT);

任何拥有更好的SQL / Wordpress foo的人都能帮我一把吗?

2 个答案:

答案 0 :(得分:0)

使用SQL时,参数注入不能用于IN逗号分隔列表 - 它只适用于该列表中的一个值。您需要将SQL语句创建为预准备语句语法之外的字符串,包括$ titles_list并置。

答案 1 :(得分:0)

好吧,我想回来给大家一个解决方案......

$titles_list = implode( "', '", $thetitles);

$order_by_results = build_order($thetitles);

$querystr = "
    SELECT wposts.* 
    FROM $wpdb->posts wposts
    WHERE post_title IN ('" . $titles_list . "') 
    AND wposts.post_status = 'publish' 
    AND wposts.post_type = 'post'
    ORDER BY CASE post_title " . $order_by_results ."
    LIMIT ".$getnumber;

build_order()函数从原始列表中获取$ thetitles并使用

格式化它们
WHEN   'n[1]'   THEN   1
WHEN   'n[2]'   THEN   2
ELSE     3      END

模式,该功能在这里:

function build_order($titlelist) {
$order_counter = 1;
$row = array();
foreach($titlelist as $title) :
    $row[] = "WHEN '" . $title . "' THEN " . $order_counter;
    $order_counter++;
endforeach;
    $row[] = "ELSE " . $order_counter . " END";

$title_order = implode( " ", $row);

if (title_order)
    return $title_order;
}

希望这将有助于将来的其他人