In mu ZF2 project I have Model using TableGateway.
Inside function responsible for fetching objects based on search criteria (city, postal_code, range, type).
Generally I fetch rows of data by simple
$rowset = $this->tableGateway->select($where);
In my MySQL database I have procedure GetObjectsInCityRange(city, range) which returns all object_id in range of geocoded city coordinates
I intend to add in the where clause condition:
WHERE object_id IN (call GetObjectsInCityRange(city, range))
Is it possible with MySQL? How write correctly $where array element to make it work?
You can call a where() method in your select object and call in() on the return value or create a where statement.
E.g.
$select = new Select();
$select->from($this->tableName)->columns(array($expression));
$where = new Where();
$where->in($identifier, $valueSet);
// or
$where->addPredicate(
new Predicate\In($identifier, $valueSet)
);
// and then
$select->where($where);
and append it to the select object.
The link below is exactly what you need I believe :)
http://framework.zend.com/manual/2.1/en/modules/zend.db.sql.html#in-identifier-array-valueset-array
Hope this helps :)
For MySQL it is suggested that you should use function instead of procedure as function can be used in any sql query while procedure is itself a query like statement. Ex.
call MyPrcedure();
SET var = MyFunction();
So you can call function in your query most of the time. However as per my knowledge function will return valid mysql data-type like varchar, int float etc. So query rows may not be available in your In query. Then only way to execute your query to convert your procedure logic to a subquery and pass inside IN statement.
WHERE object_id IN (SUB_QUERY)
Related
I need to execute my function inside a query like this
$re = $bddp->prepare("SELECT * FROM `shop`, `hours` WHERE isOpen('`hours`.`day1`') = true";
$re->execute();
hours.day1 is a varchar with opening hours of monday like this "10:00-14:00"
Function isOpen test if its open or not and return true or false
The question is who i can send hours.day1 like a variable into isOpen function in WHERE isOpen('hours.day1') ?
Its not possible to use PDO prepare or execute for this ?
In the SQL query you can use only MySQL native functions, stored functions/procedures and User-Defined Functions (UDF).
I think that you would not have a problem if the table structure was right (start-end times were in the separate columns). Then you would able to achieve your goal only with a few conditions in the WHERE part.
If the data amount (rows count) is not big, then you can just select all rows and done the validation in the PHP side.
When I execute a PDO statement, internally a result set is stored, and I can use ->fetch() to get a row from the result.
If I wanted to convert the entire result to an array, I could do ->fetchAll().
With Laravel, in the Query Builder docs, I only see a way to get an array result from executing the query.
// example query, ~30,000 rows
$scores = DB::table("highscores")
->select("player_id", "score")
->orderBy("score", "desc")
->get();
var_dump($scores);
// array of 30,000 items...
// unbelievable ...
Is there any way to get a result set from Query Builder like PDO would return? Or am I forced to wait for Query Builder to build an entire array before it returns a value ?
Perhaps some sort of ->lazyGet(), or ->getCursor() ?
If this is the case, I can't help but see Query Builder is an extremely short-sighted tool. Imagine a query that selects 30,000 rows. With PDO I can step through row by row, one ->fetch() at a time, and handle the data with very little additional memory consumption.
Laravel Query Builder on the other hand? "Memory management, huh? It's fine, just load 30,000 rows into one big array!"
PS yes, I know I can use ->skip() and ->take() to offset and limit the result set. In most cases, this would work fine, as presenting a user with 30,000 rows is not even usable. If I want to generate large reports, I can see PHP running out of memory easily.
After #deczo pointed out an undocumented function ->chunk(), I dug around in the source code a bit. What I found is that ->chunk() is a convenience wrapper around multiplying my query into several queries queries but automatically populating the ->step($m)->take($n) parameters. If I wanted to build my own iterator, using ->chunk with my data set, I'd end up with 30,000 queries on my DB instead of 1.
This doesn't really help, too, because ->chunk() takes a callback which forces me to couple my looping logic at the time I'm building the query. Even if the function was defined somewhere else, the query is going to happen in the controller, which should have little interest in the intricacies of my View or Presenter.
Digging a little further, I found that all Query Builder queries inevitably pass through \Illuminate\Database\Connection#run.
// https://github.com/laravel/framework/blob/3d1b38557afe0d09326d0b5a9ff6b5705bc67d29/src/Illuminate/Database/Connection.php#L262-L284
/**
* Run a select statement against the database.
*
* #param string $query
* #param array $bindings
* #return array
*/
public function select($query, $bindings = array())
{
return $this->run($query, $bindings, function($me, $query, $bindings)
{
if ($me->pretending()) return array();
// For select statements, we'll simply execute the query and return an array
// of the database result set. Each element in the array will be a single
// row from the database table, and will either be an array or objects.
$statement = $me->getReadPdo()->prepare($query);
$statement->execute($me->prepareBindings($bindings));
return $statement->fetchAll($me->getFetchMode());
});
}
See that nasty $statement->fetchAll near the bottom ?
That means arrays for everyone, always and forever; your wishes and dreams abstracted away into an unusable tool Laravel Query Builder.
I can't express the valley of my depression right now.
One thing I will say though is that the Laravel source code was at least organized and formatted nicely. Now let's get some good code in there!
Use chunk:
DB::table('highscores')
->select(...)
->orderBy(...)
->chunk($rowsNumber, function ($portion) {
foreach ($portion as $row) { // do whatever you like }
});
Obviously returned result will be just the same as calling get, so:
$portion; // array of stdObjects
// and for Eloquent models:
Model::chunk(100, function ($portion) {
$portion; // Collection of Models
});
Here is a way to use the laravel query builder for making the query, but to then use the underlying pdo fetch to loop over the record set which I believe will solve your problem - running one query and looping the record set so you don't run out of memory on 30k records.
This approach will use all the config stuff you setup in laravel so you don't have to config pdo separately.
You could also abstract out a method to make this easy to use that takes in the query builder object, and returns the record set (executed pdo statement), which you would then while loop over as below.
$qb = DB::table("highscores")
->select("player_id", "score")
->orderBy("score", "desc");
$connection = $qb->getConnection();
$pdo = $connection->getPdo();
$query = $qb->toSql();
$bindings = $qb->getBindings();
$statement = $pdo->prepare($query);
$statement->execute($bindings);
while ($row = $statement->fetch($connection->getFetchMode()))
{
// do stuff with $row
}
Say I have a random zend_db_select object.
How can I perform a count on that object, so I know the amount of items that meet the query.
I tried the following:
$data->TotalRecords = $select->columns(new Zend_Db_Expr('COUNT(*)'))->query()->fetch();
But this gives me the following error:
Message: No table has been specifiedfor the FROM clause
The query by itself works fine and returns a resultset.
There's a couple of ways of specifying the columns to fetch in a Zend_Db_Select. The following two product the same SQL
$select = $db->select()
->from('myTable', array())
->columns(array('TotalRecords' => new Zend_Db_Expr('COUNT(*)')));
$select = $db->select()
->from('myTable', array('TotalRecords' => new Zend_Db_Expr('COUNT(*)')));
The from method takes a first argument, the table name, and a second argument, an array of columns to fetch. If you're using an expression, you can specify a 'key' => Expr.
It's really easy to convert a Zend_Db_Select into a SQL string for debugging or use with other functions.
echo $select; // prints SELECT COUNT(*) AS `TotalRecords` FROM `myTable`
This uses a toString method, which is called automatically by Zend_Db fetch methods:
$total = $db->fetchOne($select);
echo $total; //prints the number of rows matching the query
Where $db is an instance of Zend_Db.
Use $select->__toString() method to output your generated query and see what is wrong with it.
If u dont have a from clause in your query add From() method to your select object.
If you use Zend_Db_Select, you have to call the from method to set the table name. With a Zend_Db_Table_Select, the table is passed in the constructor, so you don't need to call from.
$select = $db->select();
$select->from(
'table_name',
array('cnt' => 'count(1)')
);
I just encountered the same issue and found out what is going wrong
the Zend_Db_Select::columns functions expects an Array instead of a Object or String (when the first parameter is an String or Object it'll probably use this as main table for the columns you give but Im not sure about that.).
Changing your code to
$data->TotalRecords = $select->columns(array(new Zend_Db_Expr('COUNT(*)')))->query()->fetch();
Will fix your issue
$this->facebook_applications = Doctrine::getTable('FacebookApplication')
->createQuery('a')
->execute();
I don't understand how this works at all. Why is the query just 'a' and why does that seem to get a list of the applications?
The static method Doctrine::getTable() gets an object that represents the FacebookApplication table.
That object has a method called createQuery(), which creates a Doctrine_Query object for querying that table. The argment ('a'), specifies an alias for the table in the query.
So essentially Doctrine::getTable('FacebookApplication')->createQuery('a') creates a query that translates to SQL like:
SELECT * FROM FacebookApplication as a
Which, naturally, returns all rows from that table.
You can see it by using :
$this->facebook_applications->getSqlQuery()
I am using MVC with PHP/MySQL.
Suppose I am using 10 functions with different queries for fetching details from the database.
But at other times I may want to get only the count of the result that will be returned by the query.
What is the standard way to handle such situation.
Should I write 10 more functions which duplicate almost whole query and return only the count.
Or
Should I always return the count also with the result set
Or
I can pass a flag to indicate that the function should return count only, and then based on the flag I will dynamically generate the (select part of) query.
Or
Is there a better way?
Now that mysql supports sub-queries, you can get counts for any query using:
$count_query="SELECT COUNT(*) FROM ($query)";
How hard was that?
However this approach always means that you are running two queries instead of just the one (I'm not sure if MySQL would necessarily be able to use a cached result set for the count - try it out and see).
If you've already fetched the entire result set it'll probably be faster counting the rows in PHP than issuing another query.
There are 2 functions in MySQL which would return the number of matched rows prior to application of a limit statement:
SQL_CALC_FOUND_ROWS and FOUND_ROWS()
see
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows
C.
If you want only number of rows matched certain criteria, you shouldn't use a count of the result, but another query that select only count(*) instead.
If you need both data and it's count, why don't you just use count() on the resulting array?
another way is to use some class that can return both data and it;s count, but not different classes for the each 10 queries but one single database access class.
I'd go with the flag idea.
Writing 10 more functions and copy/pasting code does not help readability at all. If you always also return the count, that means that whenever you're only interested in the count, the database still has to generate and transmit the full result set which might be grossly inefficient.
With the flag, you'd have something like
function getData($countOnly=false) {
// ...generate FROM and WHERE clause
if ($countOnly) {
$query = 'SELECT COUNT(*) '.$query;
} else {
$query = 'SELECT field1, field2, ...'.$query.' ORDER BY ...';
}
...
}
I would generally try to have as much code as possible shared between methods. A possibility would be to :
have one select() and one count() functions
each one building the specific part of the query
and one buildFromAndWhere() function to build the parts of the query that are common.
and have select() and count() use that one
Written in pseudo-code, it could look a bit like this :
function select($params) {
return "select * "
. from()
. where($params)
. "limit 0, 10";
}
function count() {
return "count(*) as nbr "
. from()
. where();
}
function from() {
return "from table1 inner join table1 on ... ";
}
function where($params) {
// Use $params to build the where clause
return "where X=Y and Z=blah";
}
This way, you have as much common code as possible in the from() and where() functions -- considering the hard part of the queries is often there, it's for the best.
I prefer having two separate functions to select and count ; I think it make code easier to read and understand.
I don't like the ideas of one method returning two distinct data (list of results and the total count) ; and i don't really like the idea of passing a flag either : looking at the function's call, you'll never know what that parameter means.