How to print sql query in Magento 2?

by raven_corwin , in category: PHP CMS , 8 months ago

How to print sql query in Magento 2?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by herminia_bruen , 3 months ago

@raven_corwin 

To print an SQL query in Magento 2, you can use the following methods:

  1. Use the Zend_Db_Profiler class:
1
2
3
4
5
6
7
$profiler = Mage::getSingleton('core/resource')->getConnection('core_read')->getProfiler();
$profiler->setEnabled(true);

// Perform the SQL query

$query = $profiler->getLastQueryProfile();
echo $query->getQuery();


  1. Use the Varien_Db_Adapter_Pdo_Mysql class:
1
2
3
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
$sql = $connection->select()->from('table_name', array('*'));
echo $sql->__toString();


  1. Use the Mage::log() function:
1
2
3
$collection = Mage::getModel('catalog/product')->getCollection();
$sql = $collection->getSelect();
Mage::log($sql->__toString());


Note that the Mage::log() function will write the SQL query to the Magento log file, which is typically located at var/log/system.log.


I hope this helps! Let me know if you have any questions.