Site icon Hip-Hop Website Design and Development

WPDB: Update table

I am currently developing my first WordPress plugin and am currently a bit confused on how to change a record in a database.

So far I have solved it using the $wpdb::update() function:

public function toggle_status() {
    global $wpdb;
    $id = (int) $_POST["id"];
    $active = (int) $_POST["active"];
    $tablename = $wpdb->prefix . 'myplugin_table';
    $wpdb->update($tablename, array("active" => $active), array("id" => $id)); // Update record
}

Now I have learned that the way I change the database is not safe regarding SQL injection. I should rather use the $wpml::prepare() function:

$wpdb->query($wpdb->prepare("UPDATE $tablename SET active = '%s' WHERE id = '%d'", array($active, $id)));

Is the $wpdb::update() function really not safe?

According to the documentation, this is not necessary for the $wpdb functions: "$data should be unescaped (the function will escape them for you). Keys are columns, Values are values." (https://codex.wordpress.org/Data_Validation#Database).