Search code examples
phparrayscodeigniterresultset

How to access the row data produced by CodeIgniter's result() method?


Method inside the model:

public function get_fichas()
{
    $query = $this->db->query("SELECT * FROM fichas;"); 
    return $query->result();
}

Then, I'm trying to pass this data to the controller. Method on the controller:

public function listar_fichas()
{   
    $data['fichas_info'] = $this->fichas_model->get_fichas();
    $this->load->view('templates/header');
    $this->load->view('fichas/listar_fichas', $data);   
}

When I try to list the data in a view, I get the following error:

"Fatal error: Cannot use object of type stdClass as array"

Here is how I'm trying to list:

View file:

<?php foreach ($fichas_info as $row) { ?>
    <table>
        <tr>
            <td><?php echo $row['cod_produto']; ?></td>
            <td><?php echo $row['nome_produto']; ?></td>
            <td><?php echo $row['versao']; ?></td>
        </tr>
    </table>
<?php } ?>

I think I'm doing something wrong on the view. Perhaps I'm passing the data incorrectly to the view. Can someone please tell what I'm doing wrong?


Solution

  • <td><?php echo $row['cod_produto'] ;?></td>
    <td><?php echo $row['nome_produto'] ;?></td>
    <td><?php echo $row['versao'];?></td>
    

    should be:

    <td><?php echo $row->cod_produto ;?></td>
    <td><?php echo $row->nome_produto ;?></td>
    <td ><?php echo $row->versao;?></td>
    

    The result set is an object, so each column name is a property of the object. You were accessing them as an index of an array.