How to print exact sql query in zend framework ?

前端 未结 14 1966
栀梦
栀梦 2020-12-07 09:33

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

    ...
                  $select = $this->_db->select()
                    ->from($th         


        
相关标签:
14条回答
  • 2020-12-07 10:28

    from >= 2.1.4

    echo $select->getSqlString()
    
    0 讨论(0)
  • 2020-12-07 10:28

    The query returned from the profiler or query object will have placeholders if you're using those.

    To see the exact query run by mysql you can use the general query log.

    This will list all the queries which have run since it was enabled. Don't forget to disable this once you've collected your sample. On an active server; this log can fill up very fast.

    From a mysql terminal or query tool like MySQL Workbench run:

    SET GLOBAL log_output = 'table';
    SET GLOBAL general_log = 1;
    

    then run your query. The results are stored in the "mysql.general_log" table.

    SELECT * FROM mysql.general_log
    

    To disable the query log:

    SET GLOBAL general_log = 0;
    

    To verify it's turned off:

    SHOW VARIABLES LIKE 'general%';
    

    This helped me locate a query where the placeholder wasn't being replaced by zend db. Couldn't see that with the profiler.

    0 讨论(0)
  • 2020-12-07 10:31

    You can use Zend_Debug::Dump($select->assemble()); to get the SQL query.

    Or you can enable Zend DB FirePHP profiler which will get you all queries in a neat format in Firebug (even UPDATE statements).

    EDIT: Profiling with FirePHP also works also in FF6.0+ (not only in FF3.0 as suggested in link)

    0 讨论(0)
  • 2020-12-07 10:32

    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.

    0 讨论(0)
  • 2020-12-07 10:33

    you can print..

    print_r($select->assemble());
    
    0 讨论(0)
  • 2020-12-07 10:33
    $db->getProfiler()->setEnabled(true);
    
    // your code    
    $this->update('table', $data, $where);    
    Zend_Debug::dump($db->getProfiler()->getLastQueryProfile()->getQuery());    
    Zend_Debug::dump($db->getProfiler()->getLastQueryProfile()->getQueryParams());    
    $db->getProfiler()->setEnabled(false);
    
    0 讨论(0)
提交回复
热议问题