Reputation: 981
I have following table fields in the database :
id, user_id, permission_id, value, created.
I have one result of an array which may contain more than 20 different values at a time. That whole contains the permission_id
values and rest of the fields are similar. like user_id
will be only one which will be inserted same with each permission_id
and value
will be always 1
and created
is same as it would contain current date and time.
Now I am able to insert into database with following code:
$user_perms=$this->input->post('permissions');
foreach($user_perms as $perms) {
$userPerms['permission_id']=$perms;
$userPerms['user_id']=$uid;
$userPerms['value']=1;
$userPerms['created']=date("Y-m-d H:i:s");
$this->admins->insertPerms($userPerms);
}
Now it runs very well. But i want to make it more efficient and fast. As you may have noticed that i run that insert query
in the foreach loop . So, when the user will click the submit at the back end the query may run more than 30 times at a time. which is not a good idea.
Therefore, how can i insert data without loop at once ?
Upvotes: 1
Views: 486
Reputation: 14752
You can use $this->db->insert_batch()
to insert multiple rows at once:
$this->db->insert_batch(
'table_name',
array(
// first row:
array('permission_id' => 1, 'user_id' => 1, 'value' => 1, 'created' => '...'),
// second row:
array('permission_id' => 2, 'user_id' => 1, 'value' => 1, 'created' => '...')
)
);
(read more here)
However, you obviously don't avoid the foreach loop that way because you'd need to somehow create the array of data that you're passing to it ...
So, another way to optimize it is to run those inserts inside a transaction. That would (as far as SQL is concerned at least) be the equivalent of inserting them all at once in a single query, because it's COMMIT that's the most expensive operation and therefore 1 commit is faster than 20 commits.
Upvotes: 1