WPDB: Update table

Now I have learned that the way I change the database is not safe regarding SQL injection.

So I wonder where/how did you learn that?

And other than that you should check if those two POST variables are actually set, your toggle_status() code looks fine to me, and $wpdb->update() is an easy way to update a record in the database in WordPress, so you should just use that function instead of having to use the “long” version: $wpdb->query( $wpdb->prepare( "UPDATE ...", ... ) ).

And actually, if you were to use that version, then the correct syntax is:

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

I.e. Do not wrap the query value placeholders in quotes, e.g. just %s and not '%s', and for each placeholder, pass its replacement value as a direct parameter for $wpdb->prepare() and not as part of the array like you did in your code.

And yes, with $wpdb->update(), you should pass the raw data and not escaped ones, e.g. pass "foo" as-is and not escaped like \"foo\". Otherwise, the function would double-escape that escaped value as \\\"foo\\\"