How do you properly prepare a %LIKE% SQL statement?

The $wpdb->esc_like function exists in WordPress because the regular database escaping does not escape % and _ characters. This means you can add them in your arguments to wpdb::prepare() without problem. This is also what I see in the core WordPress code:

$wpdb->prepare(" AND $wpdb->usermeta.meta_key = '{$wpdb->prefix}capabilities' AND $wpdb->usermeta.meta_value LIKE %s", '%' . $this->role . '%');

So your code would look like:

$wpdb->prepare(
    "SELECT
        column_1
    FROM
        `{$wpdb->base_prefix}my_table`
    WHERE
        column_2 LIKE %s;",
    '%' . $wpdb->esc_like($number_to_put_in_like) . '%'
);

You can also add %% in your query to get a literal % (wpdb::prepare() uses vsprintf() in the background, which has this syntax), but remember that your string will not be quoted, you must add the quotes yourself (which is not what you usually have to do in wpdb::prepare().

Leave a Comment