How to manually execute SQL query in CakePHP without a model

James J picture James J · Nov 7, 2012 · Viewed 18.1k times · Source

I'm writing a quick throwaway method to import users from an old table to my new cake app. I've imported the old users table (old_users) into my cake app db. Basically I need to just do a select all form the old_users table, then loop through them and add them to the new users table using somehting like $newuser->create('old_username', 'old_password');

However, I didnt want to create a model etc for the temp table as this import will only be run once. So my question is - how can I do a basic select to get all the users from this table from a cake method within the users controller. I was thinking somehting like this:

public function admin_importOldUsers() {
        $db = $this->getDataSource();
        $db->fetchAll('SELECT * FROM old_users');
    }

But it failswith the error:

Call to undefined method UsersController::getDataSource()

I cant find much in the docs on how to query another db table (without a model) from within a controller....

Could anyone point me in the right direction?

Thanks in advance

Answer

BadHorsie picture BadHorsie · Nov 7, 2012

To manually run a standard SQL query in CakePHP without a model, you can use the query method on any model that is available to the controller (it doesn't matter which model you use):

class MyController extends AppController
{
    public function index()
    {
        $result = $this->AnyModel->query("SELECT * FROM my_table");
    }
}

CakePHP 1.3 - Models