I'm currently trying to execute custom queries in CakePHP framework, meaning instead of using CakePHP syntax, I'd like execute normal SQL query like SELECT * FROM post ORDER BY id desc.
I cannot figure out how to do it. I read several answers to the similar questions, but it still doesn't work.
As far as I understand I should put function like:
public function testx()
{
    $sql = "SELECT * FROM posts WORDER by id desc";
    return $this->query($sql);
}
to file Post in directory Model and then put this code:
$result = $this->Post->testx();
to index function in PostsController in Controller directory.
I still can't figure out how to print out the data in View/Posts/index.ctp.
Thanks in advance for any answer.
If you want to execute a delete (or any other) query without a model then you should try
$db = ConnectionManager::getDataSource('default');
$db->rawQuery("DELETE FROM table WHERE id=5");
                        public function index(){
    $this->loadModel('Post'); //or you can load it in beforeFilter()
    $data=$this->Post->query('SELECT * FROM posts ORDER by id desc');
    $this->set('data',$data);
}
In your view file index.ctp. Write Below Code
<?php
     if($data) {
          echo "<pre>";
          print_r($data);
     } else {
          echo 'no data found';
     }
?>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With