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

  1. somtam
    Posted 2 years 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?


  2. catacaustic
    very awesome
    Posted 2 years 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.


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

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

Topic Closed

This topic has been closed to new replies.

About this Topic