3

我有下拉,如下所示

<select class="selectpicker form-control" multiple name="category[]">
    <option value="1" id="MENTAL HEALTH">MENTAL HEALTH</option>
    <option value="2" id="SUICIDE SUPPORT">SUICIDE SUPPORT</option>
    <option value="3" id="HEALTH">HEALTH</option>
    <option value="4" id="SUPPORT">SUPPORT</option>
</select>

在我的控制器中,我有以下代码从下拉列表中获取该数据

public function save()
{
    $ctgry= ($this->input->post('category'));
    $orgName= ($this->input->post('InputName'));
    $streetNo= ($this->input->post('StreetNo'));
    $streetName= ($this->input->post('StreetName'));
    $suburb= ($this->input->post('Suburb'));
    $state= ($this->input->post('state'));
    $postCode= ($this->input->post('PostCode'));
    $count = count($ctgry);

    $supprtGroup = array(
        'name' => $orgName,
        'street_no' => $streetNo,
        'street' => $streetName,
        'suburb' => $suburb,
        'state' => $state,
        'pc' => $postCode
    );

    $supportgroup_id = $this->Home_Model->addSupportGroup($supprtGroup);

    $j = 0;
    i = 0;
    $sc_id = 0

    echo 'aa';//just for error checking purpose

    if ($count > 1)
    {
        echo ' aa1';//just for error checking purpose
        while ($i > $count)
        {
            echo ' aa2';//just for error checking purpose

            $support_category = array(
                'supportgroup_id' => $supportgroup_id,
                'category_id' => $ctgry[$j]
            );
            $sc_id = $this->Home_Model->addSupportrCategory($support_category);
            $i++;
            echo $sc_id;//just for error checking purpose

        }
    }
    else
    {
        echo ' aa3';//just for error checking purpose
        $support_category = array(
            'supportgroup_id' => $supportgroup_id,
            'category_id' => $ctgry[$j]
        );
        $sc_id = $this->Home_Model->addSupportrCategory($support_category);
        echo $sc_id;//just for error checking purpose
    }
    echo'bb';//just for error checking purpose
}

以下是我的模型类

function addSupportGroup($supprtGroup=NULL)
{
    $this->db->insert('support_group', $supprtGroup);
    return $this->db->insert_id();
}

function addSupportrCategory($support_category=NULL)
{
    $this->db->insert('support_category', $support_category);
    return $this->db->insert_id();
}

当从下拉列表中选择多个值时,输出如下

aa aa1bb

谁能给我一个答案,为什么会发生这种情况,如果它是从下拉列表中选择的单个值,它保存到数据库中,我会搜索每个类似的帖子,但找不到答案。

4

1 回答 1

1

我看不到$count你的问题中定义的位置,所以我不知道它的价值是什么,但是,如果你得到“aa1”作为输出,你说它大于 1。

你的while()意思是,它$i必须大于$count但 $i 等于 0,因此 while 循环不会启动。

如果您只想遍历类别,则更容易:

$supportgroup_id = $this->Home_Model->addSupportGroup($supprtGroup);

foreach ($ctgry as $cat) {
    $insert = array(
       'supportgroup_id' => $supportgroup_id,
       'category_id' => $cat 
    );

    $sc_id = $this->Home_Model->addSupportrCategory($support_category);
}

这将起作用,因为下拉列表将始终作为数组拾取。

您还应该考虑为此添加一些验证!

希望这可以帮助!

于 2015-05-24T07:57:49.957 回答