Reputation:
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.
Upvotes: 1
Views: 6827
Reputation: 94625
function insert_multiple($table,$data)
{
foreach($data as $values)
{
$this->db->insert($table, $values);
}
}
Upvotes: 0
Reputation: 25251
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.
Upvotes: 2