[wp-hackers] WP 3.5.2/multisite: How to use NOT IN in $wpdb->prepare()?
wp at andrewnacin.com
Tue Jul 16 12:52:44 UTC 2013
$wpdb->prepare() is only for preparing a query with %s, %d, or %f
If your query doesn't have a placeholder, then don't use prepare. As in:
$rows = $wpdb->get_results($wpdb->prepare("SELECT blog_id FROM
$wpdb->blogs WHERE blog_id NOT IN ($ignore) AND public = '1' AND archived =
'0' AND mature = '0' AND spam = '0' AND deleted = '0'", $ignore),
Just make sure that $ignore is is secure! As in:
$ignore = esc_sql( array( $a, $b, $c ) );
$ignore = "'" . implode( "', '", $ignore ) . "'";
Since the ignored values are IDs, then you don't *actually* need to escape
with esc_sql() here. I would still use intval() or absint(), though.
$ignore = array_map( 'absint', array( $a, $b, $c ) );
$ignore = implode( ', ', $ignore );
On Mon, Jul 15, 2013 at 10:36 PM, Micky Hulse <mickyhulse.lists at gmail.com>wrote:
> Situation and example code:
> $ignore = implode(',', array('1', '19', '21',));
> echo '<pre>';
> $rows = $wpdb->get_results($wpdb->prepare("SELECT blog_id FROM
> $wpdb->blogs WHERE blog_id NOT IN (%s) AND public = '1' AND archived =
> '0' AND mature = '0' AND spam = '0' AND deleted = '0'", $ignore),
> echo '</pre>';
> The "NOT IN ()" filter fails to ignore blog ids.
> I'm not certain, but I assume my code fails because $ignore isn't of
> the %s, %d or %f types.
> Move $ignore into the statement like so:
> ... blog_id NOT IN ($ignore) ...
> I get this PHP notice:
> PHP Notice: wpdb::prepare was called <strong>incorrectly</strong>.
> wpdb::prepare() requires at least two arguments. Please see <a
> href="http://codex.wordpress.org/Debugging_in_WordPress">Debugging in
> WordPress</a> for more information. (This message was added in version
> 3.5.) in /rgblog/html/wp-includes/functions.php on line 2962
> Reason for the notice:
> "PHP Warning: Missing argument 2 for wpdb::prepare()"
> you’re passing $id directly into the query, unprepared. And this,
> right here, is why $wpdb->prepare() now issues a warning if it isn’t
> called with more than one argument. Because you can’t prepare a query
> without more than one argument.
> With that said, how can I accomplish my goal of passing several blog
> IDs into a query that uses wpdb::prepare() (like my example above)?
> Any tips would be appreciated. :)
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
More information about the wp-hackers