wpdb prepare sql problem

时间:2013-05-26 作者:Devoted

我对wpdb prepare和sql查询有问题。如果我直接通过wpdb->get\\u results运行查询,它工作得很好。这是:

$alabala_sql = $wpdb->prepare(
    "
    SELECT * 
    FROM $wpdb->posts p 
    INNER JOIN $wpdb->term_relationships tr 
      ON p.ID = tr.object_id
    INNER JOIN $wpdb->term_taxonomy tt 
      ON tr.term_taxonomy_id=tt.term_taxonomy_id 
    inner join  $wpdb->terms t 
      on t.term_id=tt.term_id and t.slug=\'$curPageId\'
    WHERE 
      p.post_title LIKE \'$getChar%\'        
      AND p.post_type = \'filmi-i-serialii\' 
      AND p.post_status = \'publish\';
    "
);
/*Make sql query to take posts*/
$eventsPosts = $wpdb->get_results($alabala_sql);
但它不起作用。我也试过这样做:

$alabala_sql = $wpdb->prepare(
    "
    SELECT * 
    FROM $wpdb->posts p 
    INNER JOIN $wpdb->term_relationships tr 
      ON p.ID = tr.object_id
    INNER JOIN $wpdb->term_taxonomy tt 
      ON tr.term_taxonomy_id=tt.term_taxonomy_id 
    inner join  $wpdb->terms t 
      on t.term_id=tt.term_id and t.slug=$s
    WHERE 
      p.post_title LIKE $s%        
      AND p.post_type = \'filmi-i-serialii\' 
      AND p.post_status = \'publish\';
    ", $curPageId, $getChar
);
/*Make sql query to take posts*/
$eventsPosts = $wpdb->get_results($alabala_sql);
但还是没用。请告诉我哪里错了?两个变量都是字符串。当做

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

获取% 在SQL字符串中输入字符而不会混淆sprintf() 将其添加到替换字符串:

$alabala_sql = $wpdb->prepare(
    "
    SELECT *
    FROM $wpdb->posts p
    INNER JOIN $wpdb->term_relationships tr
        ON p.ID = tr.object_id
    INNER JOIN $wpdb->term_taxonomy tt
        ON tr.term_taxonomy_id=tt.term_taxonomy_id
    INNER JOIN  $wpdb->terms t
        ON t.term_id=tt.term_id and t.slug= %s
    WHERE
        p.post_title LIKE %s
        AND p.post_type = \'filmi-i-serialii\'
        AND p.post_status = \'publish\';
    ", 
    $curPageId, 
    $getChar . \'%\'
);           /* ^ like this */

结束