I am trying to run a query in AppController on a table that has no Model associated with it. I don't want to use a Model cause this query would fire on every request and I guess using a Model would make it a bit slower.
I found out in one forum that this can be achieved with the following code in CakePHP 1.3
$db = ConnectionManager::getInstance();
$conn = $db->getDataSource('default');
$conn->rawQuery($some_sql);
But this is not working in CakePHP 2.1.3. Any help would be appreciated. Thanks :)
$log = $this->User->getDataSource()->getLog(false, false); debug($log); This will show a log of all queries: $db =& ConnectionManager::getDataSource('default'); $db->showLog(); If you want to show all queries log all over the application you can use in view/element/filename.
To view records of database, we first need to get hold of a table using the TableRegistry class. We can fetch the instance out of registry using get() method. The get() method will take the name of the database table as argument. Now, this new instance is used to find records from database using find() method.
The getDataSource()
method is static in CakePHP 2.x, so you should be able to use:
$db = ConnectionManager::getDataSource('default');
$db->rawQuery($some_sql);
you should run this way
App::uses('ConnectionManager', 'Model');
$db = ConnectionManager::getDataSource('default');
if (!$db->isConnected()) {
$this->Session->setFlash(__('Could not connect to database.'), 'default', array('class' => 'error'));
} else {
$db->rawQuery($some_sql);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With