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

I’d like to use a LIKE %text% statement while still using the WordPress $wpdb class to sanitize and prepare input.

SELECT column_1 from `prefix_my_table` WHERE column_2 LIKE '%something%';

I’ve tried something like this to no avail:

Read More
$wpdb->prepare( "SELECT column_1 from `{$wpdb->base_prefix}my_table` WHERE column_2 LIKE %s;", like_escape($number_to_put_in_like));

How do you properly prepare a %LIKE% SQL statement using the WordPress database class?

Related posts

Leave a Reply

4 comments

  1. 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().

  2. You need to double percent so they are no treated like fragment markers by wpdb->prepare():

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

    PS not sure this is best/only way to do it.

  3. This is one way to do it that I’ve checked and it works:

    $search_text = "%" . $_GET['some_text'] . "%";
    
    $user_count = $wpdb->get_var( 
        $wpdb->prepare( 
            "SELECT COUNT(*) FROM mix_library WHERE ml_setting_name LIKE %s", 
            $search_text 
        ) 
    );
    

    Replace variables to suit your needs.

  4. $safe_sql = $wpdb->prepare("SELECT * FROM $wp_track_table $sql",["*yoursecretkey*".$_POST['search']."*yoursecretkey*"]);
    
    $safe_sql = str_replace("*yoursecretkey*", "%", $safe_sql);
    

    I found a suitable solution with the above codes. Definitely try it.