Support » Fixing WordPress » how to use wpdb->prepare and LIKE

  • Resolved ide79


    OK I have a problem with getting a query result with $wpdb->prepare LIKE

    $var = "benz";
    $results = $wpdb->get_results($wpdb->prepare("select model_car, type_car, engine_car FROM carstable WHERE model_car LIKE %s", $var), ARRAY_A ); ?>

    How can I make the %s (string) to be used with LIKE

Viewing 12 replies - 1 through 12 (of 12 total)
  • I think you want to set $var to ‘%benz%’ or, you may need quotes also, like this: ‘”%benz%”‘.

    What if i use $_GET[‘var’] from url?

    Use something like this:

    $var = '%' . $_GET['var'] . '%';

    Thank you very much. I tought that would be the way. Was not sure where to modify the value with get method. Because of the prepare function at the query.

    You are welcome!

    Have one more question about get method from url. Is this not a very dangerous way to get a variable to the query? should i prepare it in some way before it gets in the query (Because SQL Injection). Or does the $wpdb->prepare make the variable safe to use in the query?

    WordPress does not currently offer a “safe” facility for LIKE values. Prepare is better than nothing for now. You might be interested in the discussion at

    I don’t know what you are expecting to match, but perhaps you could limit the length, and only allow letters, digits and spaces.

    That will be probably the best way to reduce some risk of SQL injection. I think there should be a function like in DW GetSQLValueString.

    Off topic question: (mysql)
    Is it possible to make a “switch” in mysql select like this.

    WHERE cartype='honda'
    CASE %s
    WHEN 'listall' THEN
    AND subcartype like '%%' end
    AND subcartype = %s end

    // if case listall then list all honda>subcartype else get the value %s
    // Or should i make 2 queries with case statement

    Ignore the last question. That was a stupid one.
    Too little sleep too much code. 🙂

    Been there. Done that. Didn’t learn, will do again.

Viewing 12 replies - 1 through 12 (of 12 total)
  • The topic ‘how to use wpdb->prepare and LIKE’ is closed to new replies.