In reading the Zend Framework 2 Documentation: http://framework.zend.com/manual/2.0/en/modules/zend.db.sql.html two examples are given on how one might query data from the Database. For reference, they are:
To prepare (using a Select object):
use Zend\Db\Sql\Sql;
$sql = new Sql($adapter);
$select = $sql->select();
$select->from('foo');
$select->where(array('id' => 2));
$statement = $sql->prepareStatementForSqlObject($select);
$results = $statement->execute();
To execute (using a Select object)
use Zend\Db\Sql\Sql;
$sql = new Sql($adapter);
$select = $sql->select();
$select->from('foo');
$select->where(array('id' => 2));
$selectString = $sql->getSqlStringForSqlObject($select);
$results = $adapter->query($selectString, $adapter::QUERY_MODE_EXECUTE);
I was unable to find any further instruction in the documentation as to what advantages/disadvantages one method may have over the other in certain situations. I can see that if we needed to debug our SQL query, the getSqlStringForSqlObject would help us to do so. But beyond that, does anyone know a situation where one method may be better than the other?
Thanks.
I would certainly use prepareStatementForSqlObject() to prepare your statements to be executed.
prepareStatementForSqlObject() will return a StatementInterface type object.
getSqlStringForSqlObject() will get you back an actual raw SQL string.
prepareStatementForSqlObject() isn't used anywhere in the library, and probably not meant to be used externally anyway. I would stick to using the Statement Object for executing Queries if you can.
the second example is probably just to illustrate you can execute raw SQL strings if needed.