Search in This Blog

custom query in cakePHP 3.0


How to execute custom query in cakePHP


Use ConnectionManager::get() and it's method newQuery() you can pass custom sql query


Change your database information in "config\app.php" file as below:

  'Datasources' => [
        'default' => [
            'className' => 'Cake\Database\Connection',
            'driver' => 'Cake\Database\Driver\Mysql',
            'persistent' => false,
            'host' => 'localhost',
            'username' => 'root',
            'password' => '',
            'database' => 'petro_app',
            'encoding' => 'utf8',
            'timezone' => 'UTC',
            'cacheMetadata' => true,
            'quoteIdentifiers' => false,

At the top in php code file where you want to execute sql query access ConnectionManager class as below:

use Cake\Datasource\ConnectionManager;

In method run sql query as below:
File name HardSelectionController.php   with complete code

use Cake\Datasource\ConnectionManager;

class HardSelectionController extends AppController  {

    public function showhardselection() {
      $conn = ConnectionManager::get('default');
      $query = $conn->newQuery();
                ->where(['active' => true]);
    foreach ($query as $row) {
         echo $row['u_login'];