WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] $wpdb->prepare with an sql like "WHERE id IN()" (3 posts)

  1. somtam
    Member
    Posted 8 months ago #

    If I try to use a prepare with a query like

    post_id IN (50, 48, 46, 44, 42)

    if I use a placeholder for number %d, it returns only the first one.
    If I use the string placeholder, like %s, it doesn't work also, because the query becomes
    post_id IN ('50, 48, 46, 44, 42')

    is there a solution for that? or do i have just to validate the IDs by myself and use not the placeholder?

    thanks

  2. catacaustic
    Member
    Posted 8 months ago #

    That's because using the %d placeholder treats that value as a decimal number, so an array / string / etc will not work the same way. The string one also won't work in your case for exactly the reason that you're saying above.

    So yes, you are best off doing the validation yourself. In this caes it's pretty easy because all you need to do is run all of the values through intval() and you'll get a valid (and as secure as possible) value that you can use in your query.

    Eg:

    $ids = array ();
    
    foreach ($values as $val) {
        $ids [] = intval ($val);
    }
    
    $where = "WHERE post_id IN(".implode (",", $ids).")";
  3. somtam
    Member
    Posted 8 months ago #

    thanks for anwer...
    I've got it!

Reply

You must log in to post.

About this Topic

Tags