Code with problems after PHP update from 7.4 to 8.1

Discussion in 'PHP' started by Divvy, Nov 15, 2023.

  1. #1
    This code was working fine with PHP 7.4:

    (...)
    @update_post_meta($post->ID, 'discount-extra-site', array_map( 'strip_tags', $_POST['discount-extra-site'] ) );
        (...)
        <option value="<?php the_ID(); ?>" <?php if (is_array($sites_discounted) && in_array(get_the_ID(), $sites_discounted)) { echo "selected"; } ?>><?php the_title(); ?></option>
    (...)
    Code (markup):
    But the update_post_meta is not working so well after upgrade to PHP 8.1

    I mean, it saves if I add some data, but if I want to remove it don't let me...
    I can change and add more data, but don't let me remove it completely.

    It gives me the following error:

    The line 963 is:

    (...)
    @update_post_meta($post->ID, 'discount-extra-site', array_map( 'strip_tags', $_POST['discount-extra-site'] ) );
    (...)
    Code (markup):
    Any idea how to fix this, please?

    Thank you in advance
     
    Divvy, Nov 15, 2023 IP
  2. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #2
    Well, it reports that the
    $_POST['discount-extra-site']
    Code (markup):
    is null - are you sure it is actually containing anything? And is an array?
     
    PoPSiCLe, Nov 15, 2023 IP
  3. Divvy

    Divvy Well-Known Member

    Messages:
    785
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    128
    #3
    Thank you for helping me, PoPSiCLe!

    I tried to use the chatgpt to solve this and the AI gave me this code that really worked, but it seems too big!
    Do I need the entire code to make this work?

    if (isset($_POST['discount-extra-site'])) {
    $discount_extra_site = $_POST['discount-extra-site'];
    
    // Check if $_POST['discount-extra-site'] is an array and not empty
    if (is_array($discount_extra_site) && !empty($discount_extra_site)) {
    // Use array_map only if $_POST['discount-extra-site'] is an array and not empty
    $sanitized_discount_extra_site = array_map('strip_tags', $discount_extra_site);
    
    // Update post meta with the sanitized array
    update_post_meta($post->ID, 'discount-extra-site', $sanitized_discount_extra_site);
    } else {
    // If the array is null or empty, remove the post meta
    delete_post_meta($post->ID, 'discount-extra-site');
    }
    } else {
    // If $_POST['discount-extra-site'] is not set, remove the post meta
    delete_post_meta($post->ID, 'discount-extra-site');
    }
    Code (markup):
     
    Divvy, Nov 16, 2023 IP