WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] how to use wpdb->prepare and LIKE (13 posts)

  1. ide79
    Member
    Posted 4 years ago #

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

    <?php
    $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

  2. vtxyzzy
    Member
    Posted 4 years ago #

    I think you want to set $var to '%benz%' or, you may need quotes also, like this: '"%benz%"'.

  3. ide79
    Member
    Posted 4 years ago #

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

  4. vtxyzzy
    Member
    Posted 4 years ago #

    Use something like this:

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

  5. ide79
    Member
    Posted 4 years ago #

    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.

  6. vtxyzzy
    Member
    Posted 4 years ago #

    You are welcome!

  7. ide79
    Member
    Posted 4 years ago #

    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?

  8. Robert Chapin
    Member
    Posted 4 years ago #

    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 http://core.trac.wordpress.org/ticket/10041

  9. vtxyzzy
    Member
    Posted 4 years ago #

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

  10. ide79
    Member
    Posted 4 years ago #

    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.

  11. ide79
    Member
    Posted 4 years ago #

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

    SELECT * FROM CARS
    WHERE cartype='honda'
    CASE %s
    WHEN 'listall' THEN
    AND subcartype like '%%' end
    ELSE
    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

  12. ide79
    Member
    Posted 4 years ago #

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

  13. vtxyzzy
    Member
    Posted 4 years ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic