在PHP中将数据从foreach插入数据库

时间:2009-08-29 03:21:48

标签: php codeigniter

我正在使用Codeigniter框架,我有一个带输入字段的表单。当我想将输入字段的值插入数据库时​​,我使用此代码

function add($tableName)
{
    $fieldsData = $this->db->field_data($tableName); // to get all fields name of the table like (id,title,post .. )
    foreach ($fieldsData as $key => $field)
    {
        $datacc = array(  $field->name => $this->input->post($field->name) ); 
        echo $this->input->post($field->name) ; // when I submit the form I get all that data I need like (mySubjet, MyPost...)
    } // but when I insert the data it insert just the last filed like ( cat_id = 3 ) only !// and the other fields are empty ..
    $this->db->insert($tableName, $datacc);
}

所以我只得到数据库中插入的最后一个值,但当我将查询行放在foreach循环中时,如:

function add($tableName)
{
    $fieldsData = $this->db->field_data($tableName);
    $datacc = "";
    foreach ($fieldsData as $key => $field)
    {
        $datacc = array(  $field->name => $this->input->post($field->name) );
        $this->db->insert($tableName, $datacc); // inside the loop !
    }
}

它插入15条记录/行(表中的字段数)并为每一行插入一个唯一值。在第一行插入TITLE字段,在下一行插入POST字段,在第三行插入dateOfpost字段,依此类推。

2 个答案:

答案 0 :(得分:2)

你有一个名为$ datacc的数组,但每次都要重置它。你需要附加它。

function add($tableName)  
{
    $fieldsData = $this->db->field_data($tableName);
    $datacc = array(); // you were setting this to a string to start with, which is bad
    foreach ($fieldsData as $key => $field)
    {
        $datacc[ $field->name ] = $this->input->post($field->name);
    }
    $this->db->insert($tableName, $datacc);

}

这会插入一行,但会按原样构建$ datacc数组。

您应该查看http://php.net/array以了解有关数组如何工作的更多信息。

答案 1 :(得分:0)

function insert_multiple($table,$data)
{
   foreach($data as $values)
   {
      $this->db->insert($table, $values);
   }
}