How to make an SQL query that returns an object instead of an array?

Asked

Viewed 410 times

2

Not much to talk about. What I need is to know how to make a query that returns me an object instead of an array in the format:

$eventos = [
    new Evento(1, new \DateTime('2015-01-26'), 'Titulo #1'),
    new Evento(2, new \DateTime('2015-01-31'), 'Titulo #2'),
    new Evento(3, new \DateTime('2015-03-02'), 'Titulo #3'),
    new Evento(4, new \DateTime('2015-05-04'), 'Titulo #4'),
    new Evento(5, new \DateTime('2015-05-08'), 'Titulo #5'),
    new Evento(6, new \DateTime('2015-08-01'), 'Titulo #6'),
    new Evento(7, new \DateTime('2015-09-14'), 'Titulo #7'),
    new Evento(8, new \DateTime('2015-09-19'), 'Titulo #8'),
    new Evento(9, new \DateTime('2015-11-10'), 'Titulo #9')
];
  • What is the API for connection to the database?

  • you’ve seen this link, with the fetch_fields returns the object...

  • I’ll use PDO @rray

  • PDO::FETCH_OBJ in the fetch() or fetchAll() Solve it? You can do it another way

2 answers

2

Using PDO do:

$result = $con->fetch(PDO::FETCH_OBJ);

To display the results print $result->name;

2


With PDO you can transform each row returned from the bank using the constant PDO::FETCH_OBJ, a stdClass object will be created, its properties will have the same name as the database columns.

$stmt = $db->prepre($sql);
$itens = $stmt->fetchAll(PDO::FETCH_OBJ);

If your class has specific behaviors it is best to create the objects manually in a loop.

$stmt = $db->prepre($sql);
$itens = $stmt->fetchAll(PDO::FETCH_OBJ);

$eventos = array();
foreach($itens as $item){
   $e = new Evento($item->id, $item->data, $item->titulo);
   $eventos[] = $e;
   echo $e->eventoFoiAdiado();
}
  • How I printo @rray the returned object of this query and what it is echo $e->eventoFoiAdiado();?

  • @Marcosvinicius, only with FETCH_OBJ, make a foreach, and call so $item->nome_campo_DB. eventoFoiAdiado() is if your class has other methods you need to execute.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.