1

I am using Codeigniter framework and I have a form with input fields. When I want to insert the values of inputs fields into database I use this code

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);
}

so I get only the last value inserted in the database but when I put the query line inside foreach loop like:

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 !
    }
}

it insert 15 records / rows (the number of fields in the table) and insert a unique value for every row. Inserts the TITLE field in the first row, the POST field in the next row and dateOfpost field in the third and so on.

2 Answers 2

2

You have an array called $datacc, but you are resetting it every time. You need to append to it.

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);

}

This inserts one row, but builds up the $datacc array as it goes.

You should take a look at http://php.net/array to learn more about how arrays work.

Sign up to request clarification or add additional context in comments.

1 Comment

WaW ! .. I can not believe my eyes .. Finally its working !! Gregmac Thank you SO SO SO much .. I got tired of this code I tried hundreds times for 3 days 12 hours/day ! I really appreciate your help .. and Ill not forget it ! :)
0
function insert_multiple($table,$data)
{
   foreach($data as $values)
   {
      $this->db->insert($table, $values);
   }
} 

1 Comment

Hi adatapost thank you for replay .. Gregmac`s solution is working .. thank you ..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.