How to use where condition in update batch in Codeigniter - codeigniter

I want to update a multiple row using
$this->db->update_batch('mytable', $data);
But Don't Know How to give condition in this update_batch. Can I use this where?
$this->db->where('id', Multiple Ids Here);

i have code that is different from yours but it works and also it is easy to understand first put this function in your model file
in model file
function updatedata($tbname, $data, $parm)
{
return $this->db->update($tbname, $data, $parm);
}
in your controller file use like this
$this->load->model("Your_model_name");
$this->Your_model_name->updatedata('mytable',$data,$your_condition_in_array);
i hope this will help, i am sure about that this code works, please let me know that this code is worked for you.

Per the CodeIgniter documentation on update_batch()
$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name 2' ,
'date' => 'My date 2'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name 2' ,
'date' => 'Another date 2'
)
);
$this->db->update_batch('mytable', $data, 'title');
The first parameter will contain the table name, the second is an associative array of values, the third parameter is the where key.
In other words, The array contains all data for the fields to be updated plus the item used to define the "where" condition. In the above arrays the value associated with the "title" key is used. So two records are updated: One where title = 'My title' and the second where title = 'Another title'
update_batch() returns the number of rows affected.

Related

Difference between $this->db->replace() $this->db->update()

I don't get the difference between query builder's Replace and Update. Especially the documentation for Replace...
This method executes a REPLACE statement, which is basically the SQL standard for (optional) DELETE + INSERT, using PRIMARY and UNIQUE keys as the determining factor.
...but I see no indication of using a PK in the example. Am I missing some fundamental knowledge here? (I understand Update just fine).
Replace
$data = array(
'title' => 'My title',
'name' => 'My Name',
'date' => 'My date'
);
$this->db->replace('table', $data);
Update
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', $id);
$this->db->update('mytable', $data);
Thanks.
REPLACE
It's like insert. but if the primary key being inserted is the same one as another one, the old one will be deleted and the new one will be inserted.
UPDATE
Updates the current row that you tried to update.

Magento Admin formfield multiselect selected

I´m currently developing a custom module for magento thats going to list employees.
I have figured out almost everything. The only thing I got left is how the selected values is going to be highlighted.
The problem I´m having is for the backend.
I got 2 tabs per employee, one for employee data and one tab for magento categories.
1 employee can have 1 or more categories.
The database table that the categories are stored in are a non-eav table.
So my question is
What in a multiselect determines which values are selected? As it is now, only one value is selected.
I think you can do this by simply passing in an array of the id's to be selected into the 'value' attribute of the field being added for the multiselect in the _prepareForm() method. Something like the following.
$fieldset->addField('category_id', 'multiselect', array(
'name' => 'categories[]',
'label' => Mage::helper('cms')->__('Store View'),
'title' => Mage::helper('cms')->__('Store View'),
'required' => true,
'values' => Mage::getSingleton('mymodule/mymodel')->getMymodelValuesForForm(),
'value' => array(1,7,10),
));
The id of the form element (e.g. category_id) must not be an attribute in your model, otherwise when the form values get set with $form->setValues() later on, the attribute value will be overwritten.
I normally store multiple selections as a text column separated by commas much like most magento modules handles stores which requires a slightly different approach as shown below.
In the form block for the tab with the multiselect, you firstly define the element to be displayed like so in the _prepareForm() method. You then get the values from the model and set put them into the form data.
protected function _prepareForm()
{
...
$fieldset->addField('store_id', 'multiselect', array(
'name' => 'stores[]',
'label' => Mage::helper('cms')->__('Store View'),
'title' => Mage::helper('cms')->__('Store View'),
'required' => true,
'values' => Mage::getSingleton('adminhtml/system_store')->getStoreValuesForForm(false, true),
));
...
if ( Mage::getSingleton('adminhtml/session')->getMymodelData() )
{
$data = Mage::getSingleton('adminhtml/session')->getMymodelData();
} elseif ( Mage::registry('mymodel_data') ) {
$data = Mage::registry('mymodel_data')->getData();
}
$data['store_id'] = isset($data['stores']) ? explode(',', $data['stores']) : array();
$form->setValues($data);
}
I normally store the selected stores (categories as in your case) in the main model as a text column and comma separated values of ids, hence the explode.
In the controller for for the edit action, I put the model being edited into the mage registry so we can load it and it's values in the step above.
Mage::register('mymodel_data', $model);
Thanks for answering.
This is how my field looks like:
$fieldset->addField('npn_CatID', 'multiselect', array(
'label' => Mage::helper('employeelist')->__('Kategori'),
'class' => 'required-entry',
'required' => true,
'name' => 'npn_CatID',
'values' => $data,
'value' => array(3,5)
));
npn_CatID is the value in my db where the category id is saved.
I have tried to change the name and field ID but cant get it working.
When its the field id is like above ONE value is selected and its the last one inserted for the chosen employee
My data array looks likes
array(array('value' => '1', 'label' => 'USB'), array('value' => '2', 'label' => 'Memories'))

Adding custom columns in order grid (Magento 1.7.0.0)

I'm having this problem with adding custom columns in the order grid in Magento 1.7.0.0 and I was hoping you'd be able to give me a hand in here.
Basically I followed this guide http://www.atwix.com/magento/customize-orders-grid/ which explained I had to make a local version of /app/code/core/Mage/Adminhtml/Block/Sales/Order/Grid.php and make a couple of changes to have the extra columns I want. By following said guide, it said that I had to edit the function _prepareCollection() to add this line (specifying the fields I want to extract in the array)
$collection->getSelect()->join('magento_sales_flat_order_address', 'main_table.entity_id = magento_sales_flat_order_address.parent_id',array('telephone', 'email'));
Before
return parent::_prepareCollection();
And add the two columns in _prepareColumns() like this:
$this->addColumn('telephone', array(
'header' => Mage::helper('sales')->__('Telephone'),
'index' => 'telephone',
));
$this->addColumn('email', array(
'header' => Mage::helper('sales')->__('Email'),
'index' => 'email',
));
And that was it, apparently... Or maybe not, since it throws the following error when I do that:
Item (Mage_Sales_Model_Order) with the same id "XXXX" already exist
To which the solution, according to the comments underneath, was to add the following line in _prepareCollection before $this->setCollection($collection):
$collection->getSelect()->group('main_table.entity_id');
After adding the line, the Order Grid now shows the Email and Phone columns just like I want it, but turns out the pagination stopped working, it only shows the most recent 20 and it says "Pages 1 out of 1", "2 records found" on top. I can't seem to figure out why this is happening and every comment I see around doesn't go beyond the last instruction above. What could possibly be the cause of this issue?
I assume it could be replicated since I haven't made any other modifications of this model.
Alright, solved it. This is what I did:
Inspired by this answer https://stackoverflow.com/a/4219386/2009617, I made a copy of the file lib/Varien/Data/Collection/Db.php, placed it under app/core/local/Varien/Data/Collection/Db.php and copied the modifications suggested on that answer to fix the group select count error that was giving me problems above. So far it seemed to work.
However, there was a problem in the rows, when I clicked on the orders it said the Order "no longer exists", so I checked the actual url and turns out the order_id in the url was the same as the "entity_id" in the order_address table, which didn't correspond with the actual associative id of the order (parent_id). After tweaking for a long time with the MySQL query, I realized the issue was in the functions called by the _prepareColumns() and getRowUrl() functions in the /app/code/local/Mage/Adminhtml/Block/Sales/Order/Grid.php I made, since they were retrieving the wrong Id. So I made the following changes:
In _prepareColumns(), within the code corresponding to the Action column, I changed the 'getter' to 'getParentId', like this:
if (Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/view')) {
$this->addColumn('action',
array(
'header' => Mage::helper('sales')->__('Action'),
'width' => '50px',
'type' => 'action',
//~ 'getter' => 'getId',
'getter' => 'getParentId',
'actions' => array(
array(
'caption' => Mage::helper('sales')->__('View'),
'url' => array('base'=>'*/sales_order/view'),
'field' => 'order_id',
)
),
'filter' => false,
'sortable' => false,
'index' => 'stores',
'is_system' => true,
));
}
And in the getRowUrl() function, I changed the $row statement within the getUrl() function like this:
public function getRowUrl($row)
{
if (Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/view')) {
//~ return $this->getUrl('*/sales_order/view', array('order_id' => $row->getId()));
return $this->getUrl('*/sales_order/view', array('order_id' => $row->getParentId()));
}
return false;
}
And now it works like a charm. I hope this helps somebody else.
The problem is in query. Instead of this query:
$collection->getSelect()->join('magento_sales_flat_order_address', 'main_table.entity_id = magento_sales_flat_order_address.parent_id',array('telephone', 'email'));
You should use this:
$collection->getSelect()->join('sales_flat_order_address', 'main_table.entity_id = sales_flat_order_address.parent_id AND sales_flat_order_address.address_type = "shipping" ',array('telephone', 'email'));
In the table sales_flat_order_address, parent_id is duplicated. The first is for billing and the second one is for shipping. So you just need to select one of this: billing or shipping. This values are in column address_type...
Try using filter_index in the addColumn function:
$this->addColumn('telephone', array(
'header' => Mage::helper('sales')->__('Telephone'),
'index' => 'telephone',
'filter_index' => 'tablename.telephone'
));
You can find out the table name with printing out the sql query:
var_dump((string)$collection->getSelect())

Update multiple Rows in Codeigniter

I have been looking around but I have not found an answer yet. Kindly help if you know the answer.
How do you update multiple rows in CI?
In my MySQL:
I have column names:
ID, Settings Name, Settings Value ( Settings Name is Unique )
I have the ff Data:
ID = 1, Settings Name = "Hello" , Settings Value = "True"
ID = 2, Settings Name = "World", Settings Value = "Good"
and more ...
I also have a form that gets the Settings Value but I am not sure how to update it on the DB. How to update the True for the Hello being the Settings Name and update the Good for the World.
I heard about insert_batch() but is there an update_batch()?
Are you using Active record?
Yes there is an update batch: $this->db->update_batch();
$data = array(
array(
'ID' => 1 ,
'Settings Name' => 'Hello' ,
'Settings Value' => 'True'
),
array(
'ID' => '2' ,
'Settings Name' => 'World' ,
'Settings Value' => 'Good'
)
);
$this->db->update_batch('mytable', $data, 'where_key');
From the documentation:
The first parameter will contain the table name, the second is an associative array of values, the third parameter is the where key.
There is indeed an update_batch() method available in CodeIgniter already.
You can use it your example like so:
$data = array(
array(
'ID' => 1,
'Settings Name' => 'Hello',
'Settings Value' => 'True'
),
array(
'ID' => 2,
'Settings Name' => 'World',
'Settings Value' => 'Good'
)
);
$this->db->update_batch('tableName', $data, 'id');
So what you have is an array of arrays, the children basically hold the data for each row in the database. The first parameter for update_batch() is the name of the database table, the second is the $data variable and the third is the column you want to use in the WHEN clause.
Here is a simple php code for perform this operations.
<?php
function basic_update($uwi='') {
$this->load->database();
$data = array(
'ID' => 1,
'Settings Name' => 'Hello',
'Settings Value' => 'True'
);
$this->db->where('ID', '1');
$this->db->update('<table name>', $data);
$data1 = array(
'ID' => 2,
'Settings Name' => 'World',
'Settings Value' => 'Good'
);
$this->db->where('ID', '2');
$this->db->update('<table name>', $data1);
}
In $this->db->where('ID', '1'); ID is your table field and 1 is the value.
In array first parameter will contain the table name, the second parameter is an associative array of values

Codeigniter Update Multiple Records with different values

I'm trying to update a certain field with different values for different records.
If I were to use MySql syntax, I think it should have been:
UPDATE products
SET price = CASE id
WHEN '566423' THEN 49.99
WHEN '5681552' THEN 69.99
END
WHERE code IN ('566423','5681552');
But I prefer to use Active Record if it's possible.
My input is a tab delimited text which I convert into an array of the id and the desired value for each record:
$data = array(
array(
'id' => '566423' ,
'price' => 49.99
),
array(
'id' => '5681552' ,
'price' => 69.99
)
);
I thought this is the proper structure for update_batch, but it fails. Here's what I've tried:
function updateMultiple()
{
if($this->db->update_batch('products', $data, 'id'))
{
echo "updated";
}
else
{
echo "failed )-:";
}
}
And I get failed all the time. What am I missing?

Resources