Zend Framework’s database components can build and run queries without the developer’s having to touch the underlying SQL. Sometimes, though, developers need the SQL for diagnosing problems or to look for efficiencies. That SQL can be accessed with a choice of two main techniques:
getQuery() is a method of Zend_Db_Profiler and seems, along with getLastQueryProfile(), to be the standard advice for retrieving SQL of a recent query:
query = $profiler->getLastQueryProfile();
Yes, getQuery() works, but what if I’m not using the profiler, or I need to retrieve SQL before a query has run?
The “magic method” __toString() is simple and can be used either before or after the query is run. When applied to a Zend_Db_Select object, it generates an SQL string.
From the Zend_Db_Select documentation:
$select = $db->select()
$sql = $select->__toString();
// The output is the string:
// SELECT * FROM "products"
__toString() is simple to use, yet is often forgotten when discussing how to retrieve SQL from Zend_Db_Select. I recommend it.