Nike Yulistia Angreni Nike Yulistia Angreni - 3 months ago 24
PHP Question

Insert in Foreach PHP

I have PHP:

if($post['for']){
foreach($post['for'] as $value){
$saveMsgObjFor->message_id = $save;
$saveMsgObjFor->object_type_id = 4;
$saveMsgObjFor->object_ref_id = $value;
$saveMsgObjFor->object_email = null;
$saveMsgObjFor->save($update);
}
}


But it just save first loop. For twice, it show error:

Statement could not be executed (23000 - 1062 - Duplicate entry
'33' for key 'PRIMARY'


33
is field
message_object_id
and it was
auto increment
. Help me, please..

Answer

Based on the hint in this answer, it would appear that you need to explicitly set the message_object_id to null. First time round it defaults to null, but then after the save() it gets set to the auto increment value, so you need to explicitly reset it, for example:

foreach($post['for'] as $value){
    $saveMsgObjFor->message_object_id = null;
    $saveMsgObjFor->message_id = $save;