Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print exact sql query in zend framework ?

I have the following piece of code which i taken from model,

    ...
                  $select = $this->_db->select()
                    ->from($this->_name)
                    ->where('shipping=?',$type)
                    ->where('customer_id=?',$userid);
                 echo  $select; exit; // which gives exact mysql query.
            .....

When i use update query in zend like ,

$up_value = array('billing'=> '0');
$this->update($up_value,'customer_id ='.$userid.' and address_id <> '.$data['address_Id']);      

Here i want to know the exact mysql query. Is there any possible way to print the mysql query in zend ? kindly advice

like image 442
mymotherland Avatar asked Oct 11 '11 09:10

mymotherland


3 Answers

Select objects have a __toString() method in Zend Framework.

From the Zend Framework manual:

$select = $db->select()
             ->from('products');

$sql = $select->__toString();
echo "$sql\n";

// The output is the string:
//   SELECT * FROM "products"

An alternative solution would be to use the Zend_Db_Profiler. i.e.

$db->getProfiler()->setEnabled(true);

// your code
$this->update($up_value,'customer_id ='.$userid.' and address_id <> '.$data['address_Id']); 

Zend_Debug::dump($db->getProfiler()->getLastQueryProfile()->getQuery());
Zend_Debug::dump($db->getProfiler()->getLastQueryProfile()->getQueryParams());
$db->getProfiler()->setEnabled(false);

http://framework.zend.com/manual/en/zend.db.select.html

like image 128
Mark Basmayor Avatar answered Nov 09 '22 01:11

Mark Basmayor


from >= 2.1.4

echo $select->getSqlString()
like image 35
Whisher Avatar answered Nov 09 '22 01:11

Whisher


I have traversed hundred of pages, googled a lot but i have not found any exact solution. Finally this worked for me. Irrespective where you are in either controller or model. This code worked for me every where. Just use this

//Before executing your query
$db = Zend_Db_Table_Abstract::getDefaultAdapter();
$db->getProfiler()->setEnabled(true);
$profiler = $db->getProfiler();

// Execute your any of database query here like select, update, insert
//The code below must be after query execution
$query  = $profiler->getLastQueryProfile();
$params = $query->getQueryParams();
$querystr  = $query->getQuery();

foreach ($params as $par) {
    $querystr = preg_replace('/\\?/', "'" . $par . "'", $querystr, 1);
}
echo $querystr;

Finally this thing worked for me.

like image 16
Rajan Rawal Avatar answered Nov 09 '22 00:11

Rajan Rawal