Usman Ali
Usman Ali

Reputation: 572

how to save record when the value is null in cakephp?

I want to sava the record but in the for loop the next id is null, how can i save the records with this condition, the loop will be stop when it find null and save the previous records.

 foreach($record['ProductPlan'] as $value=>$key)

{
 $ProductsUser = array('product_plan_id'=>$key,'user_node_id'=>$userNodeId, 'is_active'=>1);
                            $this->$model->UserNode->ProductPlansUserNode->create();
                            $this->$model->UserNode->ProductPlansUserNode->save($ProductsUser);

                        }   

and the error is Integrity constraint violation: 1048 Column 'product_plan_id' cannot be null
and in the array

   '2'
array(
'product_plan_id' => '2',
'user_node_id' => '26',
'is_active' => (int) 1
)
'3'
array(
'product_plan_id' => '3',
'user_node_id' => '26',
'is_active' => (int) 1
)
'' // This is null how can i save previous records before null?

Upvotes: 2

Views: 1340

Answers (3)

Moyed Ansari
Moyed Ansari

Reputation: 8461

I think you are confused between $value and $key, it should be used vice versa

You need to add a check for empty or null array before inserting in to table Try this

 foreach($record['ProductPlan'] as $value=>$key){
   If($key){
   $ProductsUser = array('product_plan_id'=>$key,'user_node_id'=>$userNodeId, 'is_active'=>1);
   $this->$model->UserNode->ProductPlansUserNode->create();
   $this->$model->UserNode->ProductPlansUserNode->save($ProductsUser);  
  }

}   

Upvotes: 3

sandip
sandip

Reputation: 3289

Just use normal if . Here is the sample code:

 foreach ($record['ProductPlan'] as $value => $key) {
    if (isset($key) && $key) {
       $ProductsUser = array('product_plan_id' => $key, 'user_node_id' => $userNodeId, 'is_active' => 1);
       $this->$model->UserNode->ProductPlansUserNode->create();
       $this->$model->UserNode->ProductPlansUserNode->save($ProductsUser);
    }
 }    

Upvotes: 3

Rikesh
Rikesh

Reputation: 26421

As your error says ,

Integrity constraint violation: 1048 Column 'product_plan_id' cannot be null

You have to alter this field to allow null in db to save null records. And if you want db to descide it self a unique key for that column make it AUTO_INCREMENT. So it will take the next key if you pass null for that column.

Upvotes: 3

Related Questions