YK. toe
YK. toe

Reputation: 15

How to execute a raw SQL query on a Phalcon's controller

I tried to execute raw query within a Phalcon controller's action:

 public function showAction()
{
    $data=array();
   // header("Access-Control-Allow-Origin: *");
    $query = new Query(
        'select a.id_jenis_bu,b.jenis_bu, sum(jumlah_bu) as jumlah from CakupanBu a
        inner join JenisBu b on a.id_jenis_bu=b.id_jenis_bu
        group by a.id_jenis_bu',
        $this->getDI()
    );

    // Execute the query returning a result if any
    $bus = $query->execute();
    var_dump($bus);
    foreach ($bus as $bu) {
        $data[] = array(
            'kode' => $bu->id_jenis_bu,
            'jenis' => $bu->jenis_bu,
            'jumlah' => $bu->jumlah,
        );
    }
    var_dump($data);
   return json_encode($data);
}

I But sadly this is not working, and I ended up with an error.

Could anyone give me solution?

Upvotes: 0

Views: 966

Answers (1)

sentenza
sentenza

Reputation: 1730

Even though I strongly suggest you to move all the logic for accessing data into a Model, so to take advantage of the MVC pattern, the correct way to run a raw SQL query from a Phalcon controller is:

$query = 
    'SELECT a.id_jenis_bu,b.jenis_bu, sum(jumlah_bu) as jumlah 
     FROM CakupanBu a
     INNER JOIN JenisBu b 
     ON a.id_jenis_bu=b.id_jenis_bu
     GROUP BY a.id_jenis_bu';
$this->db->query($query);

Upvotes: 1

Related Questions