Reputation: 782
I use the following code to the database:
$attribute_R_0 = wc_get_product( $post_id );
$title_top_R_0 = isset( $_POST['custom_text_field_title_related'] ) ? $_POST['custom_text_field_title_related'] : '';
$attribute_R_0->update_meta_data( 'custom_text_field_title_related', sanitize_text_field( $title_top_R_0 ) );
$attribute_R_0->save();
but I want to use a condition to avoid creating a blank table in db, which one is correct? A or B?
A:
if ('custom_text_field_title_related') {
$attribute_R_0 = wc_get_product( $post_id );
$title_top_R_0 = isset( $_POST['custom_text_field_title_related'] ) ? $_POST['custom_text_field_title_related'] : '';
$attribute_R_0->update_meta_data( 'custom_text_field_title_related', sanitize_text_field( $title_top_R_0 ) );
$attribute_R_0->save();
}
B:
$attribute_R_0 = wc_get_product( $post_id );
$nui_1 = $attribute_14->get_meta( 'custom_text_field_title_related' );
if ($nui_1 ){
$title_top_R_0 = isset( $_POST['custom_text_field_title_related'] ) ? $_POST['custom_text_field_title_related'] : '';
$attribute_R_0->update_meta_data( 'custom_text_field_title_related', sanitize_text_field( $title_top_R_0 ) );
$attribute_R_0->save();
}
Upvotes: 1
Views: 223
Reputation: 254378
None of them… To avoid a blank entry in database table, you should use instead:
if ( isset( $_POST['custom_text_field_title_related'] ) && ! empty( $_POST['custom_text_field_title_related'] ) ) {
$attribute_R_0 = wc_get_product( $post_id );
$attribute_R_0->update_meta_data( 'custom_text_field_title_related', sanitize_text_field( $_POST['custom_text_field_title_related'] ) );
$attribute_R_0->save();
}
or better:
$field_key_R_0 = 'custom_text_field_title_related';
if ( isset( $_POST[$field_key_R_0] ) && ! empty( $_POST[$field_key_R_0] ) ) {
$attribute_R_0 = wc_get_product( $post_id );
$attribute_R_0->update_meta_data( $field_key_R_0, sanitize_text_field( $_POST[$field_key_R_0] ) );
$attribute_R_0->save();
}
Upvotes: 2