We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Phalcon

Hi, I have just started up with phalcon and want to use mysqli queries instead of PDO in phalcon. Can someone tell me how can i start with that?

edited Oct '16

If you really want to use plain queries you can go with the DB adapter itself.

Or you can use PHQL to help you generate repetative code, but you have to use additional functions to support mysql built in functions like DATE, POINT() and so on.

Hi thank u for your reply.

But can you help me with DB adapter. I am not getting that in which files do i have to make changes for that.



77.7k
Accepted
answer
edited Oct '16

You dont have to make any changes to use raw SQL, just use these methods on the db service:

class MyController extends SomeController
{
    public function indexAction()
    {
        $row = $this->db->fetchOne("SELECT * FROM table");
        $resultSet = $this->db->fetchAll("SELECT * FROM table");
        $bool = $this->db->execute("DELETE FROM table WHERE 1=0");
    }
}

No need to make changes at all. If you have setup your database connetion you will be able to use:

$this->db->query('SELECT.....');

In my case the DB service is named 'db', but you can change it to anything you want:

// Database connection
$di->set('db', function() use ($config) {
    return new \Phalcon\Db\Adapter\Pdo\Mysql([
        'host' => $config->host,
        'username' => $config->username,
        'password' => $config->password,
        'dbname' => $config->name,
        'charset' => 'utf8',
        'options'  => [
            \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
            \PDO::ATTR_PERSISTENT => true,
            \PDO::ATTR_STRINGIFY_FETCHES => false
        ]
    ]);
});

\Phalcon\Db\Adapter\Pdo\Mysql

Obviously requires PDO. Just install pdo and that's it. Mysqli is ancient and old extension, PDO is much better. Why not use it ? Phalcon ORM works only with PDO.

Thank u everyone. My problem is solved.