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

2

There is not much to talk about. What I need is to know how to do a query that returns an object to me 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')
];
    
asked by anonymous 21.09.2015 / 16:26

2 answers

2

With the PDO you can transform each row returned from the database 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 manually create objects 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();
}
    
21.09.2015 / 16:38
2

Using PDO do:

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

To display results print $result->name;

    
21.09.2015 / 16:38