Support » Plugins » Hacks » prepare() for an sql processing different number of id

  • Hello.
    I would like to use prepare() for an sql that has this structure:

    DELETE FROM {$wpdb->prefix}table WHERE id IN ("1,2,3,4,5,etc....")

    but I don’t know the number of IDs that are going to be processed.
    I can make a cycle around the number of element to output the %d I need, but I don’t know if is correct.
    Or I don’t use prepare function and sanitize the query by myself, like:

    $id_arr = array_map( 'intval', $id_arr );
    $sql = "DELETE FROM {$wpdb->prefix}table WHERE id IN (" . implode( ", ", $id_arr ) . ")";
    $result = $wpdb->query($sql);

    what do you think?
    thanks everybody!

Viewing 6 replies - 1 through 6 (of 6 total)
  • Chris Olbekson

    (@c3mdigital)

    Level 12 Bug Squasher & Forum Moderator

    prepare will parse your array variable and sanitize it for you.

    $wpdb->prepare( "DELETE FROM $wpdb->table WHERE id IN (%s)", $array );

    See this ticket for more context. http://core.trac.wordpress.org/ticket/11102

    Moderator Andrew Nacin

    (@nacin)

    Lead Developer

    #11102 was not implemented, and will likely never be implemented. (See the comments.)

    While not as clean or straightforward as we’d usually prefer, your code is proper for your use case.

    Thanks for answer.
    After reading that article I tried this:

    $sql = $wpdb->prepare("DELETE FROM  {$wpdb->prefix}table WHERE id IN (%s)", $id_arr);
    $result = $wpdb->query($sql);

    but the result is that Wp delete only 1 record and not all the one with the ID inside the array… can you help to understand where is the mistake?

    thanks!

    Moderator Andrew Nacin

    (@nacin)

    Lead Developer

    Your code, as in:

    $id_arr = array_map( 'intval', $id_arr );
    $sql = "DELETE FROM {$wpdb->prefix}table WHERE id IN (" . implode( ", ", $id_arr ) . ")";
    $result = $wpdb->query($sql);

    sorry I don’t understand… you are saying that my code is correct without using prepare()?

    Moderator Andrew Nacin

    (@nacin)

    Lead Developer

    Yes.

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘prepare() for an sql processing different number of id’ is closed to new replies.