3

我有一个包含多个字段的表单,所有这些字段都可以相乘

<input type="text" name="child_name[]" />
<input type="text" name="child_age[]" />
<input type="text" name="child_gender[]" />    
<input type="text" name="child_school[]" />

我想使用 foreach 向数据库中的表中添加多行,但每次尝试时都会出现错误提示

"Unknown column 'Array' in 'field list'"

当我打印出数据时,它会将所有字段显示为数组,所以我一定是对 foreach 语句做错了,但我不知道是什么

Array ( [child_name] => Array ( [0] => child one [1] => child two) [child_age] => Array ( [0] => 14 [1] => 13 ) [child_gender] => Array ( [0] => male [1] => female ) [child_school] => Array ( [0] => burnside [1] => summer heights high ) )

任何帮助将不胜感激!#

更新

这是我的 foreach 的代码

foreach ($_POST['child_name'] as $child_name)
    {
        $insert_children_data = array(
            'child_name' => $_POST['child_name'],
            'child_age' => $_POST['child_age'],
            'child_gender' => $_POST['child_gender'],
            'child_school' => $_POST['child_school']
        );
        $insert = $this->db->insert('portrait_children', $insert_children_data);
        return $insert;
    }
4

3 回答 3

4

试试这个(假设您的表单对于每个 child_name、child_age 等都有相同数量的元素):

for ($ix=0; $ix<count($_POST['child_name']); $ix++)
{
    $insert_children_data = array(
        'child_name' => $_POST['child_name'][$ix],
        'child_age' => $_POST['child_age'][$ix],
        'child_gender' => $_POST['child_gender'][$ix],
        'child_school' => $_POST['child_school'][$ix]
    );

    $insert = $this->db->insert('portrait_children', $insert_children_data);
    //return $insert; //you cant return here. must let the loop complete.
}
于 2013-04-09T09:35:43.397 回答
0

您正在将一个数组分配给一个键,这是不可行的,请尝试循环所有元素

foreach ($_POST as $key)<br>
{<br>
    foreach($key as $v=>$v1)<br>
    {<br>
        $s[$v] = $v1;<br>
    }<br>

}<br>
print_r($s);
于 2013-04-09T09:44:43.457 回答
0

做一个数组。数组包含特定孩子的所有数据

Array (
[0] => Array (
  [name] => child1 
  [age] => 5 
  [gender] => male
  [school] => 1school )
[1] => Array (
  [name] => child2 
  [age] => 10 
  [gender] => male
  [school] => school2 )

请尝试以下代码

$i =0;  

foreach($_REQUEST['child_name'] as $child)

{

$child1[$i]['name'] = $child;

$i++;

}

$i =0;  

foreach($_REQUEST['child_age'] as $child)

{

$child1[$i]['age'] = $child;

$i++;

}

$i =0;  

foreach($_REQUEST['child_gender'] as $child)

{

$child1[$i]['gender'] = $child;

$i++;

}

$i =0;  

foreach($_REQUEST['child_school'] as $child)

{

$child1[$i]['school'] = $child;

$i++;

} 
$insert = $this->db->insert('portrait_children', $child1);
    return $insert;
于 2013-04-09T09:46:24.817 回答