Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

how to perform Read from CRUD

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. <?php

// 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.



36.4k
Accepted
answer

Hello

I assume you have add a service db such as like this

     $di->set('db', function () {
        //connect your db
    });

`

After that you just a PDO to test it https://docs.phalconphp.com/en/latest/api/Phalcon%5Db%5Adapter%5Pdo%5Mysql.html

$connection = $this->db
//Getting all robots with associative indexes only
$robots = $connection->fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
foreach ($robots as $robot) {
    print_r($robot);
}

  //Getting all robots that contains word "robot" withing the name
  $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name",
    Phalcon\Db::FETCH_ASSOC,
    array('name' => '%robot%')
  );
foreach($robots as $robot){
    print_r($robot);
}