Reputation: 714
I have a table in my database. The table structure is as follows
I need to insert data to this table as a batch, but avoid duplicate entry (here duplicate means same combination of intCampaignID and intMobileNumber).
The following is the insert function in my model
function addToCampaign($data){
$voiceengine = $this->load->database('voiceengine', TRUE);
$scheduleData = array();
$mobiles = explode(',', $data['destinations']);
$mobilesData = array();
foreach($mobiles as $mobile){
if (trim(strlen($mobile)) > 10)
$mobile = substr(trim($mobile), -10);
else
$mobile = trim($mobile);
if(!in_array($mobile, $mobilesData)){
array_push($mobilesData, $mobile);
}
}
foreach($mobilesData as $mobile){
$campaignData = array(
'intCampaignID' => $data['campaign'],
'intMobileNumber' => $mobile);
array_push($scheduleData, $campaignData);
}
$voiceengine->insert_batch('Voice.CampaignNumbers', $scheduleData);
}
I am not sure how to do this. I searched for a solution, but all the solutions are avoiding duplicates based on key. But these fields are not key fields and I have no privilege to change the structure. Someone please help me to do this
UPDATE
I have updated my function in model
function addToCampaign($data){
$voiceengine = $this->load->database('voiceengine', TRUE);
$scheduleData = array();
$mobiles = explode(',', $data['destinations']);
$mobilesData = array();
foreach($mobiles as $mobile){
if (trim(strlen($mobile)) > 10)
$mobile = substr(trim($mobile), -10);
else
$mobile = trim($mobile);
if(!in_array($mobile, $mobilesData)){
array_push($mobilesData, $mobile);
}
}
foreach($mobilesData as $mobile){
$voiceengine->where('intCampaignID', $data['campaign']);
$voiceengine->where('intMobileNumber', $mobile);
$count = $voiceengine->count_all_results('Voice.CampaignNumbers'); // need a simple method
if($count <= 0) {
$campaignData = array(
'intCampaignID' => $data['campaign'],
'intMobileNumber' => $mobile);
array_push($scheduleData, $campaignData);
}
}
$voiceengine->insert_batch('Voice.CampaignNumbers', $scheduleData);
}
The updated function will work. But I am looking for a simple solution
Upvotes: 0
Views: 1294
Reputation: 1267
Before inserting remove the duplicate values :
$scheduleData = array_map("unserialize", array_unique(array_map("serialize", $scheduleData)));
and then run the insert_batch
function
Upvotes: 2