WordPress.org

Ready to get started?Download WordPress

Forums

prepare() for an sql processing different number of id (7 posts)

  1. somtam
    Member
    Posted 1 year ago #

    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!

  2. 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

  3. Andrew Nacin
    Lead Developer
    Posted 1 year ago #

    #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.

  4. somtam
    Member
    Posted 1 year ago #

    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!

  5. Andrew Nacin
    Lead Developer
    Posted 1 year ago #

    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);
  6. somtam
    Member
    Posted 1 year ago #

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

  7. Andrew Nacin
    Lead Developer
    Posted 1 year ago #

    Yes.

Topic Closed

This topic has been closed to new replies.

About this Topic