how to Insert Multiple data with insert_batch in codeigneitor - php

i want to insert records of fifty persons to the database at one time(this can be increase).when user click the save button data should be save at the database.what is the best way to do it?
Here is my controller
function month_end_data()
{
$data_save = array(
'employee_id' => $emp,
"annual" => $annual,
"casual" => $casual
);
$id = $this->monthend_mod->savemonthenddata($data_save);
echo json_encode(array("status" => TRUE, "id" => $id));
}
Model
class monthend_mod extends CI_Model
{
public function savemonthenddata($data_save = array())
{
if ($this->db->insert_batch('pay_monthend', $data_save)) {
return true;
} else {
return false;
}
}
}
view
<button onclick="month_end_data()" class="btn btn-danger">Save</button>

Try to send in a multidimensional array:
$data = array(
array(
'employee_id' => 'xx',
//... more fields
),
array(
'employee_id' => 'yy',
//... more fields
),
array(
//... and so on
),
);
...and then send that to your savemonthenddata()-method.

Related

last inserted id in Php codeIgniter

In my model I have return below function for get record id
function getLastInserted()
{
$query = $this->db->select("MAX(`UserID`)+1 as userid")->get("registeration");
return $query->result();
}
Now I want to pass that ID to mycontroller for record insertion
public function newregistration()
{
if ($this->form_validation->run())
{
$data = array(
'Name' => $this->input->post('Name'),
'MobileNo' => $this->input->post('MobileNo'),
'IMEINumber' => $this->input->post('IMEINumber'),
'City' => $this->input->post('City')
);
$this->adminmodel->insertregistration($data);
}
}
Now I want to access model function in controller and pass record id in data function How I do ??
set return in model and in controller write
$insert_id=$this->db->insert_id();
In Controller load your model first using
$this->load->model('model_name');
Then call to model's getLastInserted() function.
$ID = $this->model_name->getLastInserted();//you will get id here
In model return $query->row()->userid; insead return of $query->result().
Then modify the controller:
public function newregistration()
{
if ($this->form_validation->run())
{
$data = array(
'UserID'=> $this->model_name->getLastInserted(),
'Name' => $this->input->post('Name'),
'MobileNo' => $this->input->post('MobileNo'),
'IMEINumber' => $this->input->post('IMEINumber'),
'City' => $this->input->post('City')
);
$this->adminmodel->insertregistration($data);
}
}
hi i worked out the solution on last inserted id dear here the code:
controller:
function sample() {
$sid=$this->adminmodel->getLastInserted();
$this->adminmodel->newregistration( $sid);
}
model:
function getLastInserted()
{
$query = $query = $this->db->select('id')->order_by('id','desc')->limit(1)->get('employee_outs')->row('id');
return $query;
}
model:
public function newregistration($sid)
{
if ($this->form_validation->run())
{
$data = array(
'UserID'=> $sid,
'Name' => $this->input->post('Name'),
'MobileNo' => $this->input->post('MobileNo'),
'IMEINumber' => $this->input->post('IMEINumber'),
'City' => $this->input->post('City')
);
$this->adminmodel->insertregistration($data);
}
}

How to save new row with ID is auto increment in CakePHP

Hi i'm a new user with cakePHP version 2.x.x and i'm trying add new Book into table Books in Database but i can't
Please check my code below
class Book extends AppModel{
var $name = "Book";
var $primaryKey = 'ID';
var $validate = array();
public function vaildInput()
{
$this->validate = array(
// Thiet lap validate cho form
"title" => array(
"rule1" => array(
"rule" => "notempty",
"message" => "Không được để trống."
),
"rule2" => array(
"rule" => array("minlength", 5),
"message" => "Vui lòng nhập tối thiểu 5 kí tự."
),
),
"description" => array(
"rule" => "notempty",
"message" => "Không được để trống."
)
);
if($this->validates($this->validate))
return true;
return false;
}}
And Controller
public function form()
{
$this->Book->set($this->data);
if(!$this->Book->vaildInput())
{
$this->set("data", "Data không hợp lệ");
}
else
{
// Every thing is ok
if($this->request->is("post"))
{
if($this->Book->save($this->data))
{
$this->set("data", "Insert Book Success.");
}
else
$this->set("data", $this->data);
}
}
}
View
if(!empty($data))
var_dump($data);
echo $this->form->create("Book", array("action" => ""));
echo $this->form->input('ID',array('type'=>'hidden') );
echo $this->form->input("title");
echo $this->form->input("description");
echo $this->form->end("Add");
with Table Books have column ID is Primary Key with Auto_Increment, so i have a question how i can save new row Book to database ? I tried but didn't success :(
This my mistake because case insensitive. I have use title but in database is Title.

Using function from model in view

In CakePHP I've a model Customer which looks like this:
<?php
class Customer extends AppModel {
public $hasMany = array(
'Invoice' => array(
'className' => 'Invoice',
)
);
public function getDisplayName($id){
$customer = new Customer();
$customer_array = $customer->find('first', array(
'conditions' => array('Customer.id' => $id)
));
if($customer_array['Customer']['company']){
return $customer_array['Customer']['company'];
} else {
return $customer_array['Customer']['frontname'] . ' ' . $customer_array['Customer']['lastname'];
}
}
public function getFullName($id){
$customer = new Customer();
$customer_array = $customer->find('first', array(
'conditions' => array('Customer.id' => $id)
));
return $customer_array['Customer']['frontname'] . ' ' . $customer_array['Customer']['lastname'];
}
}
?>
In an other view (Project) I want to show a list of customers with there display name (because some of them have an company and others don't).
So in the ProjectController I added this:
$customers = $this->Project->Customer->find('list', array(
'fields' =>array(
'Customer.id', $this->Project->Customer->getDisplayName('Customer.id')
),
'conditions' => array(
'Customer.cloud_id' => '1'
)
));
$this->set('customers', $customers);
But then I get an MySQL error because the second field isn't a databasecolumn.
Who can help me with this question?
Your best best would be using virtual fields in your Customer model:
See the docs: http://book.cakephp.org/2.0/en/models/virtual-fields.html
<?php
class Customer extends AppModel {
public $hasMany = array(
'Invoice' => array(
'className' => 'Invoice',
)
);
public $virtualFields = array(
'display_name' => 'IF(Customer.company IS NOT NULL, Customer.company, CONCAT_WS(' ', Customer.frontname, Customer.lastname))'
);
}
?>
Then in projects controller:
<?php
$customers = $this->Project->Customer->find('list', array(
'fields' =>array(
'Customer.id', 'Customer.display_name'
),
'conditions' => array(
'Customer.cloud_id' => '1'
)
));
$this->set('customers', $customers);
?>
To answer the question more generally (here the virtual fields solutions works fine), you could rewrite the getDisplayName function and put in in your Controller.
Then you could call it from the view using
$displayName= $this->requestAction(array(
'controller'=>'CustomersController',
'action'=>'getDisplayName ')
);
echo $displayName;

Lithium applyFilter(find) for related models

One model belongs to other. I need to apply "after find" filter in child model, so I try to do:
class Parent extends \lithium\data\Model
{
public $hasMany = array(
'Childs' => array(
'to' => 'app\models\Child',
'key' => array('parent_id' => 'parent_id'),
),
);
}
// ...
class Child extends \lithium\data\Model
{
protected $_meta = array(
'source' => 'child',
'key' => 'child_id',
);
public $belongsTo = array(
'Parent' => array(
'to' => 'app\models\Parent',
'key' => 'parent_id',
)
);
}
Child::applyFilter('find', function($self, $params, $chain)
{
$entity = $chain->next($self, $params, $chain);
if ( is_object($entity) )
{
$entity->notes = empty($entity->notes) ? array() : unserialize($entity->notes);
}
return $entity;
});
Then I try to find all parents with Parent::all(array('with' => 'Child', 'conditions' => $conditions)); and filter doesn`t apply :(
What can be done?
I think what you are looking for is a filter on the Parent find method:
Parent::applyFilter('find', function($self, $params, $chain)
{
$result = $chain->next($self, $params, $chain);
if (isset($params['options']['with']) && $params['options']['with'] === 'Child') {
$result = $result->map(function($parent) {
if ($parent->child) {
$child = &$parent->child;
$child->notes = empty($child->notes) ? array() : unserialize($child->notes);
}
return $parent;
});
}
return $result;
});
I'm not sure why you expect this to work. Filters act on the class methods you apply them to.

cakephp HABTM save null field

I have a site develop in cakephp 2.0.
I have a relation HABTM to the same model like this:
class Product extends AppModel {
public $name = 'Product';
public $useTable = 'products';
public $belongsTo = 'User';
public $actsAs = array('Containable');
public $hasAndBelongsToMany = array(
'Product' => array(
'className' => 'Product',
'joinTable' => 'ingredients_products',
'foreignKey' => 'product_id',
'associationForeignKey' => 'ingredient_id',
'unique' => false
)
);
}
I want to save a record into my view with a simple form like this:
echo $this->Form->create('IngredientProduct', array ('class' => 'form', 'type' => 'file'));
foreach ($product as $prod) {
echo '<div>'.$prod['ProductAlias']['alias'].'</div>';
echo $this->Form->input('IngredientProduct.product_id', array ('type'=>'text', 'value'=> $prod['ProductAlias']['id'], 'label'=> false, 'id' => 'id'));
}
$select = '<select name="data[IngredientProduct][ingredient_id]" id="[IngredientProductIngredientId">';
foreach ($other_product as $prod2) {
$select .= '<option value="'.$prod2['ProductAlias']['id'].'">'.$prod2['ProductAlias']['alias'].'</option>';
}
$select .= '</select><br>';
echo($select);
echo $this->Form->submit('Collega', array('id'=>'link_product'));
echo $this->Form->end();
Into my controller I save in this mode:
if ($this->Product->saveAll($this->request->data)){
$this->Session->write('flash_element','success');
$this->Session->setFlash ('Prodotto collegato con successo.');
//$this->redirect(array('action'=>'edit',$alias));
}
else{
$this->Session->write('flash_element','error');
$this->Session->setFlash('Errore di salvataggio activity');
}
When I'm going to see into the database I see that ingredient:id is setting well but product_id is 0.
I have debugged my request->data and this is the array:
array(
'IngredientProduct' => array(
'product_id' => '1',
'ingredient_id' => '2'
)
)
I have print the sql query created by cakephp:
INSERT INTO `db`.`ingredients_products` (`product_id`, `ingredient_id`, `modified`, `created`) VALUES ('', 2, '2012-10-09 23:19:22', '2012-10-09 23:19:22')
Why product_id is null instead of 1?
Can someone help me?
Thanks
I think this line is wrong:
$this->Product->saveAll($this->request->data);
Try:
$this->IngredientProduct->saveAll($this->request->data);
as your form seems to ask data for a relationship, not a new product.

Categories