Wordpress 使用内爆插入多个复选框值

Wordpress Inserting multiple checkbox values using implode

我正在尝试使用此代码将我的复选框的值插入到数据库中,它可以工作,但进入数据库的唯一数据是我单击的最后一个复选框的值

表单元素:

<input type="checkbox" value="football" name="sports[]">Football
<input type="checkbox" value="running" name="sports[]">Running
<input type="checkbox" value="triathlon" name="sports[]">Triathlon

PHP:

if(isset($_POST['submit'])) {
     global $wpdb;
       $sports =$_POST['sports'];
       foreach ( $sports as $sportt) {
           $sportt;
           }
       $array = array($sportt); 
       $sport = implode(',',$array);
           }
       $wpdb->insert( 
              'user_profile', 
               array(
              'sports' => $sport));

$_POST['sports'] 作为 checked/selected 值的数组提交。所以没有必要尝试用 foreach() 和 explode() 将它变成一个数组。 您可能需要使用循环函数将每个值放入数据库。 或者你可以使用 implode('what you will glue it with', $yourArray);使数组成为要插入数据库的字符串。如果你这样做:如果你想将数据库中的字符串转换回数组,你可以使用 explode('what you glued it with', $stringToExplode);