[SOLVED]Record multiples row

Hi,

I have un checkboxlist with a list of name. I need one entry in the database by name selected.

My problem is, I only get the first checkbox or the last one.


foreach ($_POST['Clients'] as $clientId)

{

	$model->attributes=$clientId;

	$model->save();

}

$this->redirect(array('index'));

Tank you for your help and sorry for my weak english.

Damien

It’s because on first record the $model->isNewRecord is true and the record is added to the database… but on all other loops isNewRecord is false… and the record is just updated not added…

You can set $model->isNewRecord to false… or generate a new model on every loop $model=new YourModel;

When I set isNewRecord to false, nothing is recorded.

When I set isNewRecord to true, only the first one is inserted and I have this SQL error:


SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '19' for key 'PRIMARY'.

Check the documentation for save() - http://www.yiiframework.com/doc/api/1.1/CActiveRecord#save-detail

If isNewRecord is false… than an update is performed instead of insert…

You are getting the integrity constraint validation because you are trying to insert a primary key value that already exists in the database… you cannot have two equal primary key values!


foreach ($_POST['Clients'] as $clientId)

{

        $model->attributes=$clientId;

        $model->save();

        $model->setIsNewRecord(true);

}

$this->redirect(array('index'));

This is my code.

With this, the first entry is recorded and I have an sql error for the second one.

I don’t know why it don’t wan’t to increment the primary key.

it seems that you are giving a value to the primary key here… If you have an autoincrement primary key, you don’t need to give it a value for saving…

Which line give a value for the primary key ?

$clientId only contain name and email address.

The first entry is recorded with a new primary key, and it want record the second with the same id as the first one, even if I set isNewRecord to true.

In this case just add one more line


$model->id=null;

Great. It works fine now.

Thank you ;)