Zend Framework SQL update query - sql

How would I write this SQL the Zend Framework way?
UPDATE register
SET balance = (balance + 10)
WHERE added_date > 1259944184 ;
I can't find any examples of this on Zend's website or the web.
Do I need to use "Zend_Db_Expr"?

This worked for me:
$data = array(balance => new Zend_DB_Expr('balance + 10'));
$db->update('register ', $data, 'added_date > 1259944184');

acording to zend framwork documentation
use this
$data = array(
'balance' => 'balance + 10'
);
$n = $db->update('register ', $data, 'added_date > 1259944184');

Try this... make sure your model is ready.
$table = new register();
This is the model class
balance=balance+10;
$data = array(
'balance' => 'balance'
);
$where = $table->getAdapter()->quoteInto('added_date > '. 1259944184 );
You can use $where[] for multiple conditions
$table->update($data, $where);
For more details follow link

I used this to modify element order to top.
Code as follow from the table class extending Zend_Db_Table_Abstract:
$data = array('i_order' => new Zend_DB_Expr('i_order + 1'));
return $this->getAdapter()->update($this->_name, $data, "i_id != {$oCurrent->i_id} AND i_order < {$i_order}");

Related

Yii1 - CDataProviderIterator limit doesn't work

I am using criteria and CActiveDataProvider to make the query, and then I want to use CDataProviderIterator, but it seems that CDataProviderIterator is ignoring the limit.
The code so far:
$criteria = new CDbCriteria();
$criteria->select = "t.id";
$criteria->join = 'LEFT JOIN purged_files ON t.id = purged_files.project_id';
$criteria->order = "t.id asc";
$criteria->condition = " purged_files.id IS NULL AND `new_status_id` IN ('DELIVERED', 'PAID') AND `created` <= DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 180 DAY)";
$criteria->limit = 1;
$criteria->offset = 0;
$criteria->together = true;
$dataProvider = new CActiveDataProvider('Project', array(
'criteria' => $criteria,
'pagination' => false
));
$iterator = new CDataProviderIterator($dataProvider);
What seems to be wrong?
You cannot disable pagination and use CDataProviderIterator at the same time. If you look into source of CDataProviderIterator you will see that it always use pagination. That is purpose of this class - it uses pagination to avoid loading millions of records into memory at the same time. If your limit is low and loading all data into memory will not exceed some memory limits, you probably don't need to use CDataProviderIterator at all - you can fetch data directly from data provider:
foreach ($dataProvider->getData() as $project) {
$project->doSomething();
}
Or do not use data provider at all:
$models = Project::model()->findAll($criteria);
If your really need a CDataProviderIterator, you may set limit by using totalItemsCount property to override real number of records:
$dataProvider = new CActiveDataProvider('Project', array(
'criteria' => $criteria,
'totalItemsCount' => 5000,
));
Make sure that your totalItemsCount is not lower than actual number of records. You may want to query database to calculate this value.

Magento Soap api get all products sku, names, short description and image

My code is working fine but take so much time for show result because i have above 1500 products.
So any one modify my code or best way to show results
$results = $proxy->catalogProductList($sessionId);
$productData = new stdClass();
$productData->additional_attributes = array('short_description','cost');
foreach($results as $value){
$results_product = $proxy->catalogProductInfo($sessionId,$value->product_id,null,$productData);
$pro_imag = $proxy->catalogProductAttributeMediaList($sessionId, $value->product_id);
echo "";
echo "".$sno++."".$value->product_id."".$value->sku."".$value->name."".$results_product->additional_attributes[0]->value."".abs($results_product->additional_attributes[1]->value)."".abs($results_product->price)." url."' width='80px' height='80px'> ";
echo "";
}
Try the following code and use magento site for easy api examples like following, example SOAP V2 (Complex Filter)
<?php
$client = new SoapClient('http://magentohost/api/v2_soap/?wsdl');
$session = $client->login('apiUser', 'apiKey');
$complexFilter = array(
'complex_filter' => array(
array(
'key' => 'type',
'value' => array('key' => 'in', 'value' => 'simple,configurable')
)
)
);
$result = $client->catalogProductList($session, $complexFilter);
var_dump ($result);

Prestashop custom admin module draggable sort/order not working

I'm building a very simple module for Prestashop 1.6 and I added an admin interface that allows to list my records, a form to add and edit and delete.
This is working fine as you can see here:
The problem is that draggable reorder button is not draggable. Hence the reordering is not working...
According to the official docs, if you set the position option in your controller, you get the draggable functionality:
['position'] => 'position', // If set to position, the field will display arrows and be drag and droppable, which will update position in db (optional).
This is the relevant part of my module controller:
$this->fields_list = array(
'id_quicklinks' => array(
'title' => $this->l('ID'),
'align' => 'center',
'width' => 25
),
'titulo' => array(
'title' => $this->l('Titulo'),
'width' => 'auto'
)
, 'lead' => array(
'title' => $this->l('Subtitulo'),
'width' => 'auto'
),
'position' => array(
'title' => $this->l('Ordem'),
'filter_key' => 'a!position',
'position' => 'position',
'align' => 'center',
'class' => 'fixed-width-md'
),
'active' => array(
'title' => $this->l('Publicado'),
'width' => '25',
'active' => 'status'
)
);
As you can see in the print screen, is shows the handles but the drag-an-drop doesn't work. No javascript errors on the console, no nothing... And I can see in the source code that jQuery and jQueryUI are loaded. Other admin pages with reorder feature are working fine...
Any ideas?
Thanks.
Well, if anyone is interested, I managed to get this to work.
In my module admin controller, I've added (before the __construct method, right after opening the Class):
protected $position_identifier = 'id_quicklinks';
id_quicklinks is the primary key of the database table this module uses.
This enabled the drag and drop feature that I was looking for, but altough I could now drag and drop, the order was not saved in the database.
For that to work I've added two more methods adapted from the controllers/admin/AdminCarriersController.php and classes/Carrier.php:
public function ajaxProcessUpdatePositions()
{
$way = (int)Tools::getValue('way');
$id_quicklinks = (int)Tools::getValue('id');
$positions = Tools::getValue('quicklinks');
if (is_array($positions))
foreach ($positions as $position => $value)
{
$pos = explode('_', $value);
if (isset($pos[2]) && (int)$pos[2] === $id_velcroquicklinks)
{
if (isset($position) && $this->updatePosition($way, $position, $id_quicklinks))
echo 'ok position '.(int)$position.' for id '.(int)$pos[1].'\r\n';
else
echo '{"hasError" : true, "errors" : "Can not update id '.(int)$id_quicklinks.' to position '.(int)$position.' "}';
break;
}
}
}
And:
public function updatePosition($way, $position, $id)
{
if (!$res = Db::getInstance()->executeS('
SELECT `id_quicklinks`, `position`
FROM `'._DB_PREFIX_.'quicklinks`
ORDER BY `position` ASC'
))
return false;
foreach ($res as $quicklinks)
if ((int)$quicklinks['id_quicklinks'] == (int)$id)
$moved_quicklinks = $quicklinks;
if (!isset($moved_quicklinks) || !isset($position))
return false;
var_dump($moved_quicklinks['position']);
// < and > statements rather than BETWEEN operator
// since BETWEEN is treated differently according to databases
return (Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'quicklinks`
SET `position`= `position` '.($way ? '- 1' : '+ 1').'
WHERE `position`
'.($way
? '> '.(int)$moved_quicklinks['position'].' AND `position` <= '.(int)$position
: '< '.(int)$moved_quicklinks['position'].' AND `position` >= '.(int)$position.'
'))
&& Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'quicklinks`
SET `position` = '.(int)$position.'
WHERE `id_quicklinks` = '.(int)$moved_quicklinks['id_quicklinks']));
}
I hope this helps someone with the same problem.
Thank you for your solution.
It took me quite a long time to realize that ajaxProcessUpdatePositions() is somehow call by itself. For those struggling to implement that method, note that echo and var_dump() won't print anything when the method is called when moving element in your table.
Also, I found someway to optimize your code a little bit.
You could replace:
if (!$res = Db::getInstance()->executeS('
SELECT `id_quicklinks`, `position`
FROM `'._DB_PREFIX_.'quicklinks`
ORDER BY `position` ASC'
))
return false;
foreach ($res as $quicklinks)
if ((int)$quicklinks['id_quicklinks'] == (int)$id)
$moved_quicklinks = $quicklinks;
By :
if (!$moved_quicklinks = Db::getInstance()->executeS('
SELECT `id_quicklinks`, `position`
FROM `'._DB_PREFIX_.'quicklinks`
WHERE `id_quicklinks` = ' . (int) $id . '
LIMIT 1;'
))
return false;
The fewer rows (and fields) returned by the database is the best. Moreover, it remove the need of a loop in your PHP code.
You could also merge both your update queries in the same database call:
return (Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'quicklinks`
SET `position`= `position` '.($way ? '- 1' : '+ 1').'
WHERE `position`
'.($way
? '> '.(int)$moved_quicklinks[0]['position'].' AND `position` <= '.(int)$position
: '< '.(int)$moved_quicklinks[0]['position'].' AND `position` >= '.(int)$position.'
') . '; UPDATE `'._DB_PREFIX_.'quicklinks`
SET `position` = '.(int)$position.'
WHERE `id_quicklinks` = '.(int)$moved_quicklinks[0]['id_quicklinks']);
Database calls are costly operations, so reducing them to the minimum is a must. Like in your PHP code, the second query won't be executed if the first fails.
Here's how my ajaxProcessUpdatePositions() looks like:
public function ajaxProcessUpdatePositions()
{
$id = (int) Tools::getValue('id');
$positions = Tools::getValue("priority_level");
$way = (boolean) Tools::getValue('way');
//"and $id" because an ID of 0 is invalid (at least if you are using an auto-increment PK)
if (is_array($positions) and $id)
{
foreach ($positions as $position => $value)
{
$pos = explode('_', $value);
if (isset($pos[2]) && (int) $pos[2] === $id)
{
$position = (int) $position;
if ($priorityLevel = Db::getInstance()->executeS(
'SELECT `id_priority_level`,
`priority_level`
FROM `pc_job_priority`
WHERE `id_priority_level` = ' . $id . '
LIMIT 1'
)) {
Db::getInstance()->execute(
'UPDATE `pc_job_priority`
SET `priority_level` = `priority_level` '.
($way ? '- 1' : '+ 1') . '
WHERE `priority_level`' . (
$way ?
' > '. (int) $priorityLevel[0]['priority_level'] .
' AND `priority_level` <= '. $position :
' < '. (int) $priorityLevel[0]['priority_level'] .
' AND `priority_level` >= '. $position
) . ';
UPDATE `pc_job_priority`
SET `priority_level` = ' . $position . '
WHERE `id_priority_level` = ' . $id
);
}
break;
}
}
}
}

Codeigniter active record where array

I am using codeigniter and active record. I am selecting my data over WHERE with array. Any like this. But how can I insert tags '>' and '<'? It is possible?
$whereQuery['service.service_end_date'] = $start;
Thank you for replies.
This might be what you want:
Associative array method:
$array = array('name' => $name, 'title' => $title, 'status' => $status);
$this->db->where($array);
// Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
You can include your own operators using this method as well:
$array = array('name !=' => $name, 'id <' => $id, 'date >' => $date);
$this->db->where($array);
Source:
http://ellislab.com/codeigniter/user-guide/database/active_record.html
http://ellislab.com/codeigniter/user-guide/database/active_record.html
$whereQuery['service.service_end_date >'] = $start;
$whereQuery['service.service_end_date <'] = $start;
You can pass > < <> in CI where function
$this->db->where('field_name <', "Condition_value");
From Codeigniter page :
You can include an operator in the first parameter in order to control the comparison:
$this->db->where('name !=', $name);
$this->db->where('id <', $id);
// Produces: WHERE name != 'Joe' AND id < 45

how to add static elements to yii dropDownList?

echo $form->dropDownList(
$model,'categoryId',
CHtml::listData(Category::model()->findAllBySql(
'SELECT * from category where isnull(parent_id)'),
'id', 'name'),
array(
'empty'=>Yii::t('fim','Search All'),
Yii::t('fim','Jobs'),
Yii::t('fim','Training'),
Yii::t('fim','Events'),
Yii::t('fim','News')
)
);
Jobs, Training, Events and News are not appearing.
How can/should we build this, in order to add those values to the select box ?
Thanks
You cannot add static elements by using the $htmlOptions parameter. Here is how I do it:
$data = CHtml::listData(Category::model()->findAllBySql(
'SELECT * from category where isnull(parent_id)'),
'id', 'name');
// Add extra options here: I am actually prepending with this syntax,
// but you are free to append or interleave instead. Array keys are the values.
$static = array(
'jobs' => Yii::t('fim','Jobs'),
'training' => Yii::t('fim','Training'),
'events' => Yii::t('fim','Events'),
'news' => Yii::t('fim','News'),
);
echo $form->dropDownList(
$model,
'categoryId',
$static + $data,
array('empty'=>Yii::t('fim','Search All')));
For me, what i did is i added jquery code, i append an html option
$("#categoryId").append("<option value='0'>Additional Field</option>");
its less complicated and it works for me