admin管理员组

文章数量:1332896

I have several fruit checkboxes but when saving to the wpdb database it only saves the last one that it checks, variable $check receives vardump string (6) "banana" string (5) "apple"

In the database only appears apple should be banana, apple in that same field an array. Should not only save it the last marked

 foreach( $checkboxes as $check ) {
    var_dump( $check); 
}

 global $wpdb; 
 $wpdb->insert('data',array( 
      'fruit' => $check
    ));

I have several fruit checkboxes but when saving to the wpdb database it only saves the last one that it checks, variable $check receives vardump string (6) "banana" string (5) "apple"

In the database only appears apple should be banana, apple in that same field an array. Should not only save it the last marked

 foreach( $checkboxes as $check ) {
    var_dump( $check); 
}

 global $wpdb; 
 $wpdb->insert('data',array( 
      'fruit' => $check
    ));
Share Improve this question edited Jul 6, 2020 at 8:55 fuxia 107k38 gold badges255 silver badges459 bronze badges asked Jul 6, 2020 at 4:42 StymarkStymark 372 bronze badges 1
  • 1 Then you should be inserting $checkboxes, not $check, which can only be one item because it's created in the foreach loop. – Jacob Peattie Commented Jul 6, 2020 at 6:19
Add a comment  | 

1 Answer 1

Reset to default 1

This isn't a Wordpress question this is a PHP question. Your foreach loops through all the $checkboxes putting one in the $check variable each time, so your insert() call only inserts the last value for $check, because it's not inside that foreach loop.

You probably want:

global $wpdb; 
foreach( $checkboxes as $check ) {
    $wpdb->insert('data',array('fruit' => $check));
}

本文标签: Save data from a checkbox to a wpdb array