Problem trying to list error - "Trying to get property of non-object in"

0

I have the following error: Trying to get property of non-object in.

What's in this snippet of code.

<tr class="success">
      <td> <?=$reg->getServico ?></td>     ******//Erro se encontra nesta linha//************************
      <td> <?=$reg->getValor ?> </td>
      </tr>

I do not know what it is, if anyone can help me, follow the code below:

class service dao.

 <?php 
 require_once('./until/bd.class.php');
 $objBd = new bd();
 $con = $objBd->conecta_mysql();

class ServicoDAO{

     public function listar_servico( ){
     global $con;

     $servico_vo = new ServicoVO();
     $query = ("SELECT * FROM servico ");
     $stmt = $con->query($query);

     while ($rs= $stmt->fetch_array()) {
          $servico_vo->setIdServico($rs['id_servico']) ;
          $servico_vo->setServico($rs['nome_servico']) ;
          $servico_vo->setValor($rs['valor']);
          return $rs;
      }      
    }
}

Page that displays values

    <body>

<div class="container">

       <div class="page-header">
         <h1>Listar Serviço</h1> 
       </div>


       <table class="table table-striped table-bordered table-hover table-condensed  ">

         <thead>
           <th>Produto</th>          
           <th>Fabricante</th> 
           <th>Preço</th> 
         </thead>

         <tbody>
          <?php

           $CPDAO = new ServicoDAO();
           $query = $CPDAO->listar_servico();

           foreach($query as $reg):


          ?>
          <tr class="success">
          <td> <?=$reg->getServico ?></td>     ******//Erro se encontra nesta linha//************************
          <td> <?=$reg->getValor ?> </td>
          </tr>


        </tbody>
      <?php 

      endforeach;
      ?>
      </table>


</body>
    
asked by anonymous 19.01.2017 / 00:50

1 answer

4

Your system-list () method does not return an object, but an array. But there is one detail: when you give a return $ rs there within the while, you are at the same time interrupting the loop. This way the while will stop and set the return $ rs to your method as soon as you run the first record.

Do as follows:

    $registros = array();
    while ($rs= $stmt->fetch_array()) {
              $servico_vo->setIdServico($rs['id_servico']) ;
              $servico_vo->setServico($rs['nome_servico']) ;
              $servico_vo->setValor($rs['valor']);
              $registros[] = $rs;
          }

   return (object) $registros; // Isso irá converter seu array $registros para um objeto
    
19.01.2017 / 01:58