Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute custom query in CakePHP

Tags:

sql

php

cakephp

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.

like image 223
Celebris Avatar asked Nov 30 '22 19:11

Celebris


2 Answers

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");
like image 21
Gurpreet Singh Avatar answered Dec 04 '22 05:12

Gurpreet Singh


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';
     }
?>
like image 94
K.Raj. Avatar answered Dec 04 '22 03:12

K.Raj.