简体   繁体   English

复选框值未正确保存在数据库中

[英]check box value not saved properly in database

I write this from in Codeigniter as a form_view.php .我从 Codeigniter 中将其写为form_view.php

<?php echo form_open('form'); ?>

<h5>Man</h5>
<input type="checkbox" name="options[]" value="m"/>

<h5>Lady</h5>
<input type="checkbox" name="options[]" value="f" />

<h5>Username</h5>
<input type="text" name="username" value="" size="50" />

<div><input type="submit" value="Submit" /></div>

</form>

And then I add this data to the database like this:然后我将这些数据添加到数据库中,如下所示:

  $data=array(
            'type'=> $_POST['options[]'],
            'name'=> $_POST['name']
            );
    $this->db->insert('user_data',$data);

The name field is ok.名称字段没问题。 But the type field has nothing.但是类型字段什么都没有。 I can not find the error.我找不到错误。 Please help me.请帮我。

Assuming that you want multiple values to be stored with comma (as separator) between them假设您希望在多个值之间使用逗号(作为分隔符)存储多个值

$data=array(
        'type'=> implode(',', $_POST['options']),
        'name'=> $_POST['name']
        );

Remove [] from options.从选项中删除[]

$_POST['options'] will be an array. $_POST['options']将是一个数组。 You may have to join the values to a string.您可能必须将值连接到字符串。

A few suggestions:几点建议:

  1. If neither one is checked the value will not be submitted to the database, so you need a default.如果两者都没有选中,则该值将不会提交到数据库,因此您需要一个默认值。
  2. Consider using a radio type instead of checkbox.考虑使用单选类型而不是复选框。 Except for some rare folks, I don't think too many people are going to be both man and lady.除了一些稀有的人,我认为不会有太多人会同时成为男人和女人。
  3. Change $_POST['options[]'] to $_POST['options']将 $_POST['options[]'] 更改为 $_POST['options']

Make制作

'type'=> $_POST['options[]']

as作为

'type'=> $_POST['options']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM