Search code examples
phpwordpressinsertprepared-statement

Wordpress - insert as prepared query vs $wpdb->insert_id


I have created a simple plugin. It has a configuration site in the backend and some functions for the user site. I need to save some user choices into database. On the beginning I used $wpdb->insert() and $wpdb->update() methods, but after I read https://codex.wordpress.org/wpdb_Class#Protect_Queries_Against_SQL_Injection_Attacks I want to change it into $wpdb->query($wpdb->prepare()) .

But how can I get id of the just inserted row without new select query? if I use $wpdb->insert() I have this id in $wpdb->insert_id, but if I use $wpdb->query() this field is empty...


Solution

  • Using $wpdb->insert() and $wpdb->update() you are implicitly using $wpdb->prepare() function and its protection.

    For example the WordPress $wpdb->update() function has in the final two lines:

    $sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres );
    return $this->query( $this->prepare( $sql, array_merge( array_values( $data ), array_values( $where ) ) ) );
    

    So, to get the inserted ID and be protected, I recommend you use $wpdb->insert().