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

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.

Related

How to use where condition in update batch in 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.

Doctrine DBAL increment

how can I increment a value?
$app->db->update('videos', array(
'views' => 'views + 1'
), array(
'id' => $id
));
It doesn't work in many ways I tried.
A better approach could be to use the method executeUpdate()
$app->db->executeUpdate("UPDATE videos SET views=views+1 WHERE id=?", array($id));
Edit 2022
The API is working but marked deprecated. Use executeStatement() instead of executeUpdate()
You have to ask the db for the current value of views first, then increment the value and save the new value into db.
$result = $app->db->fetchAssoc('SELECT views FROM videos WHERE id = ?', array($id));
$result['views']++;
$app->db->update('videos', array('views' => $result['views']), array('id' => $id));

How to add categories in Joomla 2.5

Does anyone know how to properly insert new content categories to the DB programatically?
For each post in the categories table, there is also a post saved in the assets table with lft and rgt set.
Is there any native Joomla class I can use for this instead of plain SQL?
Please Please Only use the native classes, which categories will handle for you seamlessly. As soon as you add categories the whole thing will be handled automagically. Just look at any core component to see how.
It is not easy to update the assets table using sql, it is all very specifically managed and part of a complex series of foreign keyed tables.
Extend JTable or JTableContent to handle this.
Here is some code I just whipped together that just uses the JTableCategory class, so it can be used simply on the front or admin side of Joomla
$table = JTable::getInstance('category');
$data = array();
// name the category
$data['title'] = $title;
// set the parent category for the new category
$data['parent_id'] = $parent_id;
// set what extension the category is for
$data['extension'] = $extension;
// Set the category to be published by default
$data['published'] = 1;
// setLocation uses the parent_id and updates the nesting columns correctly
$table->setLocation($data['parent_id'], 'last-child');
// push our data into the table object
$table->bind($data);
// some data checks including setting the alias based on the name
if ($table->check()) {
// and store it!
$table->store();
// Success
} else {
// Error
}
Naturally you would want to get the data pieces set correctly, but these are the core ones to set.
Here is a function I've created just for this purpose, after some digging & experimenting.
It uses core classes, so it needs an access to them (for me it's basically a part of Joomla component).
Mind, it's for Joomla 3, for Joomla 2.5 and before, you need to change JModelLegacy to JModel.
function createCategory( $name, $parent_id, $note )
{
JTable::addIncludePath( JPATH_ADMINISTRATOR . '/components/com_categories/tables' );
$cat_model = JModelLegacy::getInstance( 'Category', 'CategoriesModel' );
$data = array (
'id' => 0,
'parent_id' => $parent_id,
'extension' => 'com_content',
'title' => $name,
'alias' => '',
'note' => $note,
'description' => '',
'published' => '1',
'access' => '1',
'metadesc' => '',
'metakey' => '',
'created_user_id' => '0',
'language' => '*',
'rules' => array(
'core.create' => array(),
'core.delete' => array(),
'core.edit' => array(),
'core.edit.state' => array(),
'core.edit.own' => array(),
),
'params' => array(
'category_layout' => '',
'image' => '',
),
'metadata' => array(
'author' => '',
'robots' => '',
),
);
if( !$cat_model->save( $data ) )
{
return NULL;
}
$categories = JCategories::getInstance( 'Content' );
$subcategory = $categories->get( $cat_model->getState( "category.id" ) );
return $subcategory;
}
You can perhaps use the save() in category.php file.
File location: root\administrator\components\com_categories\models\category.php
It saves the form data supplied to it!
The JOS_assets table is to store the ACL for each asset that is created.
If you do not update this table while programatically creating the category, the default ACL will apply. And when later you open and save the category in the administrative panel, the ACL will be updated as it should have been by core Joomla!.
You can create an SQL query very easily though and update the asset table as well. Its easy to understand once you open the table's content in phpmyadmin.

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())

Inserting dates to Oracle database through Zend_Db

I am trying to add an entry to an Oracle table which has a date field. So far, I've only been able to do it like this:
$createdDate = $entry->createdDate->toString('yyyy-MM-dd');
$data = array(
'ID' => $entry->id,
'STATE' => $entry->state,
'CREATED_DATE' => new Zend_Db_Expr("to_date('$createdDate', 'YYYY-MM-DD')")
);
$this->_getGateway()->insert($data);
Is there a better way? This solution smells dirty to me.
You should be able to do this instead:
$createdDate = $entry->createdDate->toString('yyyy-MM-dd');
$data = array(
'ID' => $entry->id,
'STATE' => $entry->state,
'CREATED_DATE' => new Zend_Db_Expr("date '$createdDate'")
);
$this->_getGateway()->insert($data);
The only difference is the use of an ANSI date literal in line 5.

Resources