[wp-hackers] $wpdb->prepare syntax problem

Austin Matzko if.website at gmail.com
Mon Oct 26 18:23:56 UTC 2009


On Mon, Oct 26, 2009 at 1:10 PM, Ade Walker <photofantaisie at gmail.com> wrote:
> This doesn't =>
>
> $pages_found = $wpdb->get_results(
>        $wpdb->prepare( "SELECT ID,post_title FROM $wpdb->posts WHERE
> $wpdb->posts.ID IN( %s )", $pages_selected )
>        );
>
> It just finds the first page ID in the $pages_selected string.
>
> I've searched high and low, but can't find out what I'm doing wrong. No
> error in php error log either.
>
> Any pointers gratefully received. :-)

The problem is that you're sending this string to MySQL:

SELECT ID,post_title FROM wp_posts WHERE wp_posts.ID IN( '6,22,31,43' )

When you want

SELECT ID,post_title FROM wp_posts WHERE wp_posts.ID IN( 6,22,31,43)

Since you know the data to be sanitized has to be integers (assuming
it does need to be sanitized--ie the integers are coming from user
input),
a more direct alternative to doing this is the following:

$pages_selected = array(6,22,31,43);
$pages_found = $wpdb->get_results(
   sprintf("SELECT ID,post_title FROM $wpdb->posts WHERE
$wpdb->posts.ID IN( %s )", implode(',', array_map('intval',
$pages_selected) ) )
);


More information about the wp-hackers mailing list