Use raw queries in phalconphp

In Laravel I can write :

// select * from table users without having any Model. just raw queries.
$users = DB::table('users')->get();

But In phalcon, I can't find a way to run raw queries without involving any Model. just running a sql query. any help?

edited May '14

You can use the db service (provided that is what you called it when you registered it) from the Di container.

Then it is as simple as:

$sql         = "SELECT * FROM users";
$connection = $this->db;
$data       = $connection->query($sql);
$results    = $data->fetchAll();

Who tell that you can't? :) In previous topic I send you the fastest solution which I know.

I never need that but I think that you can deal it by getting PDO instance. In services.php you should have something like this:

//Setup the database service
$di->set('db', function(){
    return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        "host" => "localhost",
        "username" => "root",
        "password" => "123456",
        "dbname" => "",

Next check the API of Mysql adapter: There are examples of use raw queries.

thanks, what if my Class doesn't have access to db ? I am going to run this query inside a custom validator. and a custom validator is implemented ValidatorInterface and I can't write $this->db inside custom validator methods. in order to get DI , I can call \Phalcon\DI::getDefault() is there any similar way to get $connection ? for example: \Phalcon\DB::getDefault() !!

edited May '14

\Phalcon\DI::getDefault()->getDB() should works.

Or this:

$di = \Phalcon\DI::getDefault();
$db = $di['db']



is it true that raw sql is 10 times faster than Model::find()? This is what I get :(


edited Mar '15

Yes, I find PHQL 10x slower with even simple queries.

select * from user where concat(ext_prefix,ext_code) = 0015555;

0.031 sec from raw SQL; 0.3xx sec by PHQL

The table has only 1 row.


is it true that raw sql is 10 times faster than Model::find()? This is what I get :(


these answers on this article are very helpful. Tried to do those 3 query methods ( ::find() etc , query builder , phql ) , none of them satisfy my need to do queries. so to summarize what i get from these comments, what i implement on my script is :

$sql            = "SELECT * FROM someTable"
$di             = \Phalcon\DI::getDefault();
$db             = $di['db'];
$data           = $db->query( $sql );
$results        = $data->fetchAll();

it works well, thank guys