Reputation: 41
I have this function,
public function storeVals($vals)
{
$vals = explode(",", $vals);
foreach ($vals as $val)
{
$val = array('input'=>$val);
$this->db->insert('input', $val);
}
}
The function basically receives a string e.g: This,Is,An,Example
Then it turns the string into an array with "," as a delimiter.
Then it loops through the array and inserts the data into the DB.
Code Igniter, I think, already has the functionality to do this.
File: system/database/drivers/mysql/mysql_driver.php
function _insert_batch($table, $keys, $values)
{
return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values);
}
Any ideas on how I can use insert_batch() instead of looping and inserting will be highly appreciated.
Thank you.
Upvotes: 0
Views: 1039
Reputation: 16117
In CodeIgniter, You can use batch_insert
as:
public function storeVals($vals)
{
$vals = explode(",", $vals);
$yourArr = array();
foreach ($vals as $val)
{
$yourArr[] = array('input'=>$val); // store values in array
}
$this->db->insert('tableName', $yourArr);
}
You can also follow the CI example:
$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name' ,
'date' => 'Another date'
)
);
$this->db->insert_batch('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')
CI 3 User Guide (Batch Insert)
Upvotes: 1