Faisal
Faisal

Reputation: 408

How to retrieve data from database Phalcon php

I'm using tutorial-master https://docs.phalconphp.com/en/latest/reference/tutorial.html the Create step from CRUD is awesome, I can input data to database. But I don't understand how to generating data from table using query.

this code didn't work because I use $application = new Application($di); not micro.

// Retrieves all robots $app->get('/api/robots', function () use ($app) {

$phql = "SELECT * FROM Robots ORDER BY name";
$robots = $app->modelsManager->executeQuery($phql);

$data = array();
foreach ($robots as $robot) {
    $data[] = array(
        'id'   => $robot->id,
        'name' => $robot->name
    );
}

echo json_encode($data);

});

I want to have $query="SELECT * FROM ospos ORDER BY ospoId"; and output $data = array(); echo jsone_encode($data) and resulting same result as micro code.. please help Thank you.

Upvotes: 2

Views: 2780

Answers (2)

Aravind Pillai
Aravind Pillai

Reputation: 771

UPDATE: your above query using models.

$robots = Robots::find([
    'order' => 'name'
]);

Upvotes: 3

ThaLioN
ThaLioN

Reputation: 53

I couldn't find any satisfying answer so i thought of commenting how i did this.
In a controller do the following:

use Phalcon\Mvc\Controller;
$this->aricleModel = new Articles();

class IndexController extends Controller
{
    public function indexAction()
    {
        $articles = Articles::find();

        if ($articles) {
            foreach ($articles as $article) {
               echo $article->title;
               echo "<br>";
            }
        }
    } 
}

Assuming you already made the model. the key is this: $this->aricleModel = new Articles(); Without it foreach won't work.

Upvotes: 1

Related Questions