We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

how to perform Read from CRUD

I'm using tutorial-master https://docs.phalcon.io/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.



58.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.phalcon.io/en/latest/api/Phalcon_Db_Adapter_Pdo_Mysql.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);
}