Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP 2.1.x - Run a query without any models in AppController

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 :)

like image 939
Atul Dravid Avatar asked Jun 15 '12 09:06

Atul Dravid


People also ask

How can I get SQL query in cakephp?

$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.

How can I get data from cakephp?

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.


2 Answers

The getDataSource() method is static in CakePHP 2.x, so you should be able to use:

$db = ConnectionManager::getDataSource('default');
$db->rawQuery($some_sql);
like image 84
dhofstet Avatar answered Oct 30 '22 18:10

dhofstet


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);
    }
like image 24
Manish Patel Avatar answered Oct 30 '22 18:10

Manish Patel