Search in This Blog

Run custom sql query in CakePHP 3.0

Problem:

How to Run custom sql query in CakePHP 3.0

Solution & Example:

File : src\Model\Table\ArticlesTable.php
<?php
namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Datasource\ConnectionManager;
class ArticlesTable extends Table
{
    var $conn;
    public function initialize(array $config) {
        $this->conn = ConnectionManager::get('default');
    }
    function get_all_users($id) {
        $stmt = $this->conn->prepare('SELECT * from users WHERE id>= :id');
        $stmt->bind( ['id' => $id], ['id' => 'integer']);
        $stmt->execute();
        return $stmt->fetchAll('assoc');
     } 
}
?>

File: src\Controller\ArticlesController.php
<?php
namespace App\Controller;

use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
//use MyClass\MyClass;
use MyLib\UtilClass;

 class ArticlesController extends AppController
 {
     public $helpers = array('Html', 'Form');
     public function index() {

    }
    public function showarticles(){
         $data = $this->Articles->get_all_users(3);
         $this->set('data',$data);
    }
}


File: src\Template\Articles\showarticles.ctp
<?php
foreach ($data as $row){
               echo '<br/>'.$row['username']. '-------' . $row['password'];
         }
?>









Previous
Next Post »