prepare() not working

When I do this:

$transients = $wpdb->get_col(
    "
    SELECT     option_name
    FROM       $wpdb->options
    WHERE      option_name
    LIKE       '_transient_wb_tt_%'
    "
);

It works fine, but when I use prepare like so:

Read More
$transients = $wpdb->get_col( $wpdb->prepare(
    "
    SELECT     option_name
    FROM       %s
    WHERE      option_name
    LIKE       '_transient_wb_tt_%'
    ",
    $wpdb->options
) );

It doesn’t work, what am I doing wrong here?

Related posts

Leave a Reply

2 comments

  1. I agree with @bainternet. You don’t need $wpdb->prepare. There isn’t any user supplied content.

    The answer to the question is that to get a wildcard % to pass through prepare you need to double it in your code.

    LIKE  '_transient_wb_tt_%%'
    

    Try that or this if you want a good look at the generated query:

    var_dump($wpdb->prepare("
        SELECT     option_name
        FROM       %s
        WHERE      option_name
        LIKE       '_transient_wb_tt_%%'
        ",
        'abc')); 
    die;
    

    Other than being unnecessary, using $wpdb->prepare like this won’t work. The attempt to use prepare to swap in the tablename will result in a tablename with quotes around it. That is invalid SQL. The query should be simple:

    SELECT     option_name
    FROM       {$wpdb->options}
    WHERE      option_name
    LIKE       '_transient_wb_tt_%%'
    
  2. From Codex

    $wild = '%';
    $find = 'only 43% of planets';
    $like = $wild . $wpdb->esc_like( $find ) . $wild;
    $sql  = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_content LIKE %s", $like );
    

    The essential part is -> “$like = $wild . $wpdb->esc_like( $find ) . $wild;”