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

在PHP中将数据从foreach插入数据库,php,codeigniter,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 => $fi

我正在使用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
字段,依此类推。

您有一个名为$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数组


您应该查看以了解有关阵列如何工作的更多信息。

WaW。。我不敢相信我的眼睛。。终于它开始工作了!!格雷格马克非常感谢你。。我厌倦了这个代码,我试了3天12小时/天数百次!我真的很感谢你的帮助。。我也不会忘记的!:)你好,adatapost谢谢你的重播。。格雷格马克的解决方案正在发挥作用。。非常感谢。
function insert_multiple($table,$data)
{
   foreach($data as $values)
   {
      $this->db->insert($table, $values);
   }
}