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

Atul Dravid
  • 1,055
  • 3
  • 14
  • 30
  • 1
    using a model doenst make it any slower if you run just a query (using query() of the model) – mark Jun 15 '12 at 10:11
  • 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. – Borislav Sabev Jun 17 '12 at 07:51
  • To retrive your sql-query's data in this context, see http://stackoverflow.com/q/21612950/287948 – Peter Krauss Feb 06 '14 at 21:09

3 Answers3

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);
Kamlesh
  • 5,233
  • 39
  • 50
dhofstet
  • 9,934
  • 1
  • 36
  • 37
  • 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 ? – deck john Nov 26 '12 at 10:49
  • 6
    You may need `App::uses('ConnectionManager', 'Model');` as well – Richard Feb 28 '13 at 12:41
  • Any way to do this with prepared statements? – Ray Oct 15 '13 at 20:29
  • 1
    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. – Tomas Gonzalez Mar 17 '15 at 23:05
  • second line will be `$db->fetchAll($sql);` for getting result directly. – Dharmesh patel Jan 19 '17 at 08:40
  • THANK YOU `DHOFSTET` AND `RICHARD`, your suggestions worked for me to solve my issue :) – Kamlesh Aug 18 '23 at 07:42
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);
    }
Manish Patel
  • 1,877
  • 1
  • 14
  • 15
3

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

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

$db = ConnectionManager::getDataSource('default');
$data = $db->query($some_sql);
Kamlesh
  • 5,233
  • 39
  • 50
rajesh_kw
  • 1,572
  • 16
  • 14