views:

353

answers:

2

Hello everybody !

I use 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 lik ( 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 databse .. 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 .. ex. insert TITLE Field in the frist row , POST Field in the next row and dateOfpost Field in the third and so on ..

Sorry for my POOR English :)

Any Help ?

THanks in advance !

+1  A: 

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.

gregmac
WaW ! .. I can not believe my eyes .. Finally it`s 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 I`ll not forget it ! :)
ahmad
A: 
function insert_multiple($table,$data)
{
   foreach($data as $values)
   {
      $this->db->insert($table, $values);
   }
}
adatapost
Hi adatapost thank you for replay .. Gregmac`s solution is working .. thank you ..
ahmad