Zend Framework 2 and SELECT count(*) query - php

I'm trying to do a query like this using Zend Framework 2:
SELECT count(*) as num FROM mytable
Here's the code I'm using to build my select statement (bear in mind I've imported the necessary classes):
$select = new Select();
$select->from('mytable')
->columns(array('num'=>'count(*)'), false);
This code doesn't work because the resulting query is as follows:
SELECT [count(*)] AS [num] FROM [mytable]
...which throws the following error:
Invalid column name 'count(*)'
This is caused by the square brackets around count(*). How can I get this to work properly, basically to have count(*) instead of [count(*)] in the SQL. Also, I know that you can do it with just a regular query, but I need this to work with the Select object. As far as I know, this used to work with the previous versions of Zend, I've seen plenty of solutions for those, but nothing for Zend Framework 2.

Somebody on another forum was kind enough to give me the answer for this. This is how it's done:
$select->columns(array('num' => new \Zend\Db\Sql\Expression('COUNT(*)')));

Yes, without new \Zend\Db\Sql\Expression('COUNT(*)'), just COUNT(*) leads to the following error statement:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'albs.COUNT(*)' in 'field list'
Having the
new \Zend\Db\Sql\Expression('COUNT(*)')
resolved it.

Could you try this code?
$this->num = $select->columns(array('num' => new \Zend\Db\Sql\Expression('COUNT(*)')));
return $this->num;

Related

Sql query in yii2

I would like to execute such a command:
SELECT number.phone_number
FROM number
LEFT JOIN ordered_number
ON ordered_number.number_id=number.id
WHERE ordered_number.order_id=123
with Yii2. I do this:
$numery = Number::find()
->select('number.phone_number')
->leftJoin('ordered_number', ['ordered_number.number_id' => 'number.id'])
->where(['ordered_number.order_id' => 123])
->createCommand()
->rawSql;
But I get then this:
'SELECT `number`.`phone_number` FROM `number` LEFT JOIN `ordered_number` ON `ordered_number`.`number_id`='number.id' WHERE `ordered_number`.`order_id`=123'
Which doesn't work. When I put the first thing right into my base, I get 4 results, which is correct. But when I do (I think exactly the same) with Yii, I have troubles, because it is null. The only differences between what I have written and what appears after rawSql, are ` and '.
Sorry, I've just read docs for this method - it should be:
->leftJoin('ordered_number', 'ordered_number.number_id = number.id')
because using the where() kind of conditions with array leads to comparing field to string.
Maybe this link could help you a lot , the comments of ActiveRecord.

New Zend framework changes in Zend/Db/Sql/columns causes problems

Our framework sits on top of the Zend framework. A change in the way columns() is working causes problems with our database calls. Before, it was fine to do something like:
$distanceFormula = "$earthRadius*ACOS(COS(RADIANS($lat)))";
$select->columns(array('distance' => $distanceFormula));
This created a query:
SELECT `items`.*, 6371*ACOS(COS(RADIANS(51.985103)) AS `distance`
NOW it creates a query:
SELECT `items`.*, `6371*ACOS(COS(RADIANS(51.985103))` AS `distance`
columns() puts ` (apostrophe) around everything so we get the following error:
Zend_Db_Statement_Mysqli_Exception
Mysqli prepare error: Unknown column '6371*ACOS.... etc
Is there a way to tell columns not to put the formula between apostrophes?
I found that if the formula is entered as Zend_Db_Expr, everything works fine.
$distanceFormula = new Zend_Db_Expr("($earthRadius*ACOS(COS(RADIANS($lat))");
$select->columns(array('distance' => $distanceFormula));

Zend: Select object: How do I replace the selected columns set by from()?

first of all, that's what I'm trying to do:
In one of my classes in the library I want to count the total amount of rows of a search result. The class uses a select object set by the appendant model of the search result. My problem is now, this select() has already set the requested columns by from(), but to simply count the rows I just want to select the id, because the website has to to be performant. I can't simply change the values of the object, because I'm using it in the library and the variables are protected. Unfortunately, Zend has no function for the mySql count command and I don't want to use static mySql code, because it could be, that we switch our database system in the future.
Now here's my question:
Is there any possibility by Zend_Select how I could change the selected columns?
Try this:
$select->reset(Zend_Db_Select::COLUMNS)
->from('thetable', 'COUNT(*)');
replacing the 'thetable' with the correct table name.
This is from a project and isn't tested, but one of these should work.
$select->from(array("table_name" => "table_name"), array("my_col" => "COUNT(id)"));
OR
$select->from(array("table_name"), array("my_col" => "COUNT(id)"));
This is the same as
SELECT COUNT(id) as my_col FROM table_name
Hope that helps
Jake
This one didn't work for me (I needed to select only from one joined table):
$select->reset(Zend_Db_Select::COLUMNS)
->from('thetable', 'COUNT(*)');
Maybe because I had some joins. But nevertheless, here's the solution: to use reset() and then columns():
$select->setIntegrityCheck(false)
->from(['t1' => 'table1'])
->join(['t2' => 't2'], 't1.id = t2.t1_id')
->reset(Zend_Db_Select::COLUMNS)
->columns('t1.*');
Just FYI, the version of Zend Framework is 1.12
To use a mysql command in a select, you need to use Zend_Db_Expr:
$select = $this->select()
->from('myTable', new Zend_Db_Expr('COUNT(id) as count'));
echo $select; //SELECT COUNT(id) as count FROM myTable;

If in Sum combined in SQL query, and Yii ActiveRecord

First of all, sorry for my English. I need some help with this. Recently I started my first project with Yii, and everything is great, framework seems to be perfect, but I have a little problem with selecting records from the database using ActiveRecord.
Let's say that I have following code:
$criteria = new CDbCriteria();
$criteria->select = '*, user.*, sum(if(points > 0, 1, 0)) as rank_points, sum(points) as all_points, count(*) as count_all';
$criteria->group = 'user_id';
$criteria->order = 'all_points desc';
$users = Types::model()
->with('user')
->findAll($criteria);
I have problems with this
sum(if(points > 0, 1, 0)) as rank_points
when I'm using it, I get the following error:
Active record "Types" is trying to select an invalid column "sum(if(points > 0". Note, the column must exist in the table or be an expression with alias.
The problem is that this query is correct, and I can use it manually, or (I haven't tried but I think it should work) with query builder. I'm determined to do this with AR, so here is my question; is it possible, to do this as stated? Am I doing something wrong, or is it a more complicated problem?
Thanks in advance for every reply.
Just specify the select as a array
$criteria->select=array('*', 'sum(if(points > 0, 1, 0)) as rank_points','sum(points) as all_points', 'count(*) as count_all');
The problem with your code is that as your select parameter is a string, Yii try to get all columns by exploding with a , and the , in your IF statement makes yii to think it as two seperate select values

Drupal - How to get SUM of rows

I want to do a simple select with a SUM of several rows in Drupal, but I can't seem to figure out how to do that. I know there are more ways to do a query in Drupal (one of them is writing the actual query, but I don't want that).
Here is the code I have:
$query = db_select("node","n");
$query->fields("n", array("nid","likes" => "SUM(likes)"));
But apparently Drupal strips my brackets and I get the following error:
1054 Unknown column 'n.SUMlikes' in 'field list'
Could anyone help me? Is there something like $query->sum()?
You'd be best off using an expression:
$query = db_select('node', 'n')
->fields('n', array('nid'));
$query->addExpression('SUM(likes)', 'likes');
The first argument is the expression, the second the alias.
Hope that helps

Categories