Problem with sql in zend framework - zend-framework

I wanted to get the sql query like SELECT numbers FROM table ORDER BY numbers+0; in zend framework.
I am new to zend. Can anyone please help me on this.
Thank you.

What about this:
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select()->from('table','numbers')->order(new Zend_Db_Expr('numbers+0'));
var_dump($select->assemble());
//outputs:
//string 'SELECT `table`.`numbers` FROM `table` ORDER BY numbers+0' (length=56)
new Zend_Db_Expr is needed because without it, ZF will add 'ASC' to your query:
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select()->from('table','numbers')->order('numbers+0');
var_dump($select->assemble());
//outputs:
//string 'SELECT `table`.`numbers` FROM `table` ORDER BY `numbers+0` ASC' (length=62)
Hope this helps.

Related

zend framework subquery

I am using zend framework 1.12. I have following query to run.
"SELECT name,(select count(*) from org_quote_template_items where org_quote_template_items.quote_template_id = org_quote_templates.`id` ) as total_line_item FROM `org_quote_templates`"
In my model file , I created it like this. following is my model file.
class default_Model_DbTable_QuoteTemplates extends Zend_Db_Table_Abstract
{
/**
* Name of the original db table
*
* #var string
*/
protected $_name = 'org_quote_templates';
public function getAllTemplate($where){
$select = $this->select();
$subquery = " (SELECT COUNT(*) FROM org_quote_template_items WHERE org_quote_template_items.quote_template_id = org_quote_templates.`id` )";
$select->from(array($this), array('org_quote_templates.*','total_line_items' => new Zend_Db_Expr($subquery)));
$select = $select->where('organization_id = ?',$where['org_id']);
$adapter = new Zend_Paginator_Adapter_DbSelect($select);
$paginator = new Zend_Paginator($adapter);
$paginator->setItemCountPerPage(
Zend_Registry::get('config')->paginator->general);
pr($adapter);
exit;
}
}
I am getting following error when I run the code.
" exception 'Zend_Db_Table_Select_Exception' with message 'Select query cannot join with another table' "
please let me know what should I do ?
There is an error in your request. You should have:
$select = $this->select ();
$subquery = "(SELECT COUNT(*) FROM dtempls WHERE order_id = orders.id)";
$select->from ($this, array (
'id',
'total_line_items' => new Zend_Db_Expr ($subquery)
));
I think you have to use setIntegrityCheck(false) for accomplishing that. Check this link
You can try this way in zend
$this->select()
->setIntegrityCheck(false)
->from(array('oqt' => 'org_quote_templates'),array('total_line_item'))
->joinLeft(array('oqti' => 'org_quote_template_items'), 'oqti.quote_template_id = oqt.id', array(count(*) as count))

Zend framework - how to write group by query

I use zend framework and can't write in model next sql query:
SELECT `id_user`,`system_role`,count(`system_role`)
FROM `favorites`
group by `id_user`,`system_role`
How to do this?
$db = new Zend_Db_Table('favorites');
$select = $db->select()
->from('favorites', array('id_user', 'system_role', 'COUNT(system_role)'))
->group('id_user', 'system_role');

convert sql query to Zend DB query

I have tow table :
article,sub_categories
how to convert this query to zend Db query join
$sql="
SELECT article.*, sub_categories.name_arabic AS sub_category_name_arabic, sub_categories.name_english AS sub_category_name_english, article.sub_category_id AS sub_categories_id FROM article
LEFT JOIN sub_categories ON article.sub_category_id = sub_categories.id
WHERE article.active = 1
";
Please need help
Thanks with regard
This should do the trick:
$db->select()
->from('article', array('*', 'sub_categories_id' => 'sub_category_id')
->joinLeft(
'sub_categories',
'article.sub_category_id = sub_categories.id',
array('sub_category_name_arabic' => 'name_arabic', 'sub_category_name_english' => 'name_english'))
->where('article.active = 1');

Need help with Zend_db update

Currently I'm working with Zend framework and I need help with Zend_db update in Zend_Db_Table_Abstract class.
Here is my SQL statement
UPDATE user
SET password = '$password',
`enter code here` WHERE email = '$email'
Here is my code in zend_db
public function updatePassword($password,$email)
{
$data = array(
'password' => $password
);
$where = "email = '". $email ."'";
$this->update($data, 'email = '.$email);
}
This only work if I update using int id as my where clause but I wanted to use a email string as a where clause.
Can someone please help me the best way to achieve this?
I wanted to be secure and avoid SQL Injection attack
Thanks so much in advance.
You approach only works with integer values, because the way you concat the where string does not escape the value. So if you do
'email = '.$email
It will product an sql string like this if you use the string "hello world"
WHERE email = hello world
This is an invalid SQL statement so the update does not happen. What you want to produce is a where clause like this
WHERE email = 'hello world'
There are multiple ways to do this, but the safest way to do that via Zend Framework is described in the reference manual under "Example #24 Updating Rows Using an Array of Arrays".
$data = array(
'password' => $password
);
$where['email = ?'] = $email;
$this->update($data, $where);
This code might help you :
public function updateDetails($data, $emailId)
{
$where = array('email = ?' => $emailId);
$this->update($data, $where);
}
Please let me know if you still face the problem.....?

Zend framework group by

I'm trying to do a group by using Zend framework. Here's my code:
$table = new TableClass();
$select = $table->select();
$select->from ("table", array("date", "column1" => "sum(column1)"));
$select->group ( array ("date") );
$results = $table->fetchAll ($select);
$result = $results[0];
$date = $result->date;
$column1 = $result->column1;
TableClass extends 'Zend_Db_Table_Abstract'.
I can see the query by looking at the mysql query log. The query is well formed - column1 is named in the query and the results look correct if I run the query in mysql workbench.
I cannot access the data in 'column1' - I always get this exception:
Uncaught exception 'Zend_Db_Table_Row_Exception' with message 'Specified column "column1" is not in the row'
I can however access the date column without issue.
I tried:
accessing the columns by array index:
$result[0]
but you get an exception (can't access the columns by index).
not using a column alias:
$select->from ("table", array("date", "sum(column1)"));
$column1 = $result["sum(column1)"];
but you get an exception (no such column "sum(column1)").
throwing in a Zend_Db_Expr:
"column1" => new Zend_Db_Expr ( "sum(column1)" )
but this doesn't help.
Some other examples I have seen suggest the use of the column names without aggregate functions, ie. "column1" instead of "sum(column1)" but that doesn't seem to me to be the answer - the query doesn't have any aggregate functions in it so mysql won't know what to do with it.
Any help appreciated.
Firstly, a quick tip for working with Zend_Db_Select (and by extension Zend_Db_Table_Select), you can view the generated SQL by invoking the toString method. It is vital to verify that your code generates the correct query before working with a result set:
$select = $table->select();
$select->from ("table", array("date", "column1" => "sum(column1)"));
$select->group ( array ("date") );
$sql = (string) $select; //Retrieve SQL as a string
Or simply
die($select); //print SQL
I wrote the following test script using your example and have no problems:
class Table extends Zend_Db_Table_Abstract
{
protected $_primary = 'id';
protected $_name = 'table';
}
$db = Zend_Db::factory('Pdo_Mysql', array(
'dbname' => 'test',
'username' => 'root',
'password' => '',
'host' => 'localhost'
));
$table = new Table($db);
$select = $table->select();
$select->from ($table, array("date", "column1" => new Zend_Db_Expr("sum(column1)")));
$select->group ( array ("date") );
$sql = (string) $select;
echo $sql;
$results = $table->fetchAll ($select);
$result = $results[0];
$date = $result->date;
$column1 = $result->column1;
echo '<br>' . $date . ': ' . $column1;
Use Zend_Debug::dump($result); to inspect data inside the Zend_Db_Table_Row if necessary.
In my case the SQL generated is as follows:
SELECT `table`.`date`, sum(column1) AS `column1` FROM `table` GROUP BY `date`