【问题标题】:How to add multiple selected values into a single column in PHP CodeIgniter?如何在 PHP CodeIgniter 中将多个选定值添加到单个列中?
【发布时间】:2019-06-23 17:43:16
【问题描述】:

我正在做一个项目,我需要使用 Php CodeIgniter 将多个选定的值添加到单个列中。 这是实际的问题陈述: 我有一个 INT 列 total_persons 来存储总人数(即 5)和一个 VARCHAR 列 person_names 来存储这 5 个人的姓名。

要从下拉列表中选择多个用户,我使用的是 Select2 库。 但是当我提交数据时,会弹出以下错误

人名字段是必需的。 当然是因为我在表单上设置了验证规则如下:

$this->form_validation->set_rules('person_names','Person Names','required');

我不明白为什么选择有5个用户名时不会占用任何值。

如果我添加单个用户的 ID(将列保持为 INT)而不是多个选定值,它可以正常工作并在 DB 中发送数据。但是当我尝试存储多个用户名时,它会抛出我上面粘贴的错误。

这是我的 Expense.php 控制器代码

    function add()
    {   
        $this->load->library('form_validation');

        $this->form_validation->set_rules('expense_type','Expense Type','required');
        $this->form_validation->set_rules('person_names','Person Names','required');
        $this->form_validation->set_rules('total_persons','Total Persons','required');
        $this->form_validation->set_rules('expense_amount','Expense Amount','required');
        $this->form_validation->set_rules('expense_details','Expense Details','required');
        $this->form_validation->set_rules('date_added','Date Added','required');

        if($this->form_validation->run())     
        {   
            $params = array(
                'expense_type' => $this->input->post('expense_type'),
                'total_persons' => $this->input->post('total_persons'),
                'person_names' => $this->input->post('person_names'),
                'expense_amount' => $this->input->post('expense_amount'),
                'expense_details' => $this->input->post('expense_details'),
                'date_added' => $this->input->post('date_added'),
                'update_date' => $this->input->post('update_date'),
            );

            print_r($params);
            exit();

            $expense_id = $this->Expense_model->add_expense($params);
            redirect('expense/index');
        }
        else
        {
            $this->load->model('Expense_type_model');
            $data['all_expense_type'] = $this->Expense_type_model->get_all_expense_type();

            $this->load->model('User_model');
            $data['all_users'] = $this->User_model->get_all_users();

            $data['_view'] = 'expense/add';
            $this->load->view('layouts/main',$data);
        }
    }  

Expense_Model.php

    function add_expense($params)
    {
        $this->db->insert('expense',$params);
        return $this->db->insert_id();
    }

view.php

    <div class="col-md-6">
        <label for="person_names" class="control-label"><span class="text-danger">*</span>Person Names</label>
        <div class="form-group">
            <select name="person_names[]" class="form-control multiselect" multiple="multiple">
                <option value="">select user</option>
                    <?php 
                        foreach($all_users as $user)
                        {
                            $selected = ($user['user_name'] == $this->input->post('person_names')) ? ' selected="selected"' : "";

                            echo '<option value="'.$user['user_name'].'" '.$selected.'>'.$user['user_name'].'</option>';

                        } 
                    ?>
           </select>

            <span class="text-danger"><?php echo form_error('person_names');?></span>
        </div>
    </div>

如果我没有遗漏一些关键点,代码应该在 user_name 字段中添加五个名称,如下所示? [“user1”、“user2”、“user3”、“user4”、“user5”] (这是我的假设,如果我猜错了请见谅)

谁能帮我弄清楚我在哪里犯了错误?

非常感谢。

【问题讨论】:

    标签: php codeigniter jquery-select2


    【解决方案1】:

    CodeIgniter 表单验证类支持use of arrays as field names。为了使用它,您需要在验证规则中包含[]

    $this->form_validation->set_rules('person_names[]','Person Names','required');
    

    还有表单错误:

    form_error('person_names[]')
    

    编辑

    为了将数组保存在单个列中,您可以先json_encode 它,以获取 json 格式的字符串,稍后您可以使用json_decode 将数据作为数组检索:

    $params = array(
        'expense_type' => $this->input->post('expense_type'),
        'total_persons' => $this->input->post('total_persons'),
        'person_names' => json_encode($this->input->post('person_names')),
        'expense_amount' => $this->input->post('expense_amount'),
        'expense_details' => $this->input->post('expense_details'),
        'date_added' => $this->input->post('date_added'),
        'update_date' => $this->input->post('update_date'),
    );
    

    【讨论】:

    • 它对我有用。谢谢!这是 view.php 文件中的一个错字我不好。
    • 现在它不会在编辑表单中设置选定的名称。当我进入编辑页面时,所有字段都显示了选定的值(从数据库中获取),但 person_names 字段为空。我必须重新选择用户名才能编辑表单。
    【解决方案2】:

    通过这种方式,您可以将多个人的 ID 保存在单个列中,方法是用空格 分隔它们。

    您可以通过将 ids 放入数组并使用 jquery 将其展开并显示在多个选择字段中来获取保存的 ids。

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <select class="form-control" id="alertrecepients" name="alertrecepients" multiple size="10">
     <?php
        if(!empty($users)){
            foreach ($users as $cl){
     ?>
       <option value="<?php echo $cl->userId ?>"
    <?php 
       $x = 0;
       $paramArray31=explode(' ',$alertrecepients);
       $limit= count($paramArray31);
       while($x <= $limit-1) {
          if ($paramArray31[$x] == $cl->userId) {
            echo "selected";
          }
          $x++;
       }
    ?>>
    <?php echo $cl->name ?></option>
    <?php }} ?>
    </select>
    
    <script>
        $( "select[name='alertrecepients']" )
        .change(function() {
        var str = "";
        $( "select[name='alertrecepients'] option:selected" ).each(function() {
        str += $( this ).val() + " ";
        });
        $( "#selectedrecepients" ).val( str );
        })
        .trigger( "change" );
    </script>
    
    <input type="hidden" value="<?php echo $alertrecepients; ?>" name="selectedrecepients" id="selectedrecepients" />
    
    I am not familiar with snippet, so i am posting answer like this.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      • 2016-05-25
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多