Nike Yulistia Angreni Nike Yulistia Angreni - 1 year ago 140
PHP Question

Insert in Foreach PHP

I have PHP:

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

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

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

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

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download