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

3

20

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

Nearly answered 15/6, 2012 at 9:45 Comment(3)
using a model doenst make it any slower if you run just a query (using query() of the model)Vollmer
What exactly do you need to get from the database on every request? This also means doing a database request for each and every request to the application. This would increase DB load. If you're loading some configuration it may be better to load it from a file and "Objectifying" it.Sloat
To retrive your sql-query's data in this context, see https://mcmap.net/q/662353/-cake-2-x-retrive-data-from-rawquery/287948Annorah
N
35

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

App::uses('ConnectionManager', 'Model');
    
$db = ConnectionManager::getDataSource('default');
$db->rawQuery($some_sql);
Naamann answered 15/6, 2012 at 13:53 Comment(6)
i did the same thing bit shows me the error message which is mentioned below. Only variables should be assigned by reference. can you tell me that what changes still i have to do ?Forward
You may need App::uses('ConnectionManager', 'Model'); as wellOfficialism
Any way to do this with prepared statements?Paradisiacal
I tried this using CakePHP 2.6.3 and it only returned an object with the query, but not the result. Instead, I used $model->query('SELECT * FROM table'); That gave me the result I expected.Ethelinda
second line will be $db->fetchAll($sql); for getting result directly.Exactitude
THANK YOU DHOFSTET AND RICHARD, your suggestions worked for me to solve my issue :)Braud
B
9

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);
    }
Bonina answered 11/12, 2013 at 11:2 Comment(0)
R
3

rawQuery will not return data, use $db->query instead.

App::uses('ConnectionManager', 'Model');

$db = ConnectionManager::getDataSource('default');
$data = $db->query($some_sql);
Racer answered 3/7, 2016 at 6:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.