View data display with Codeigniter

Asked

Viewed 415 times

2

I’m trying to present the data from my View database. I followed the various tutorials I found on the internet but none of them could meet me :/.

Model

public function get_titles() {
    $title = $this->db->get('TB_TITLES');
    return $title->result_array();
}

Controller

public function titulosCadastrados($page = 'titulosCadastrados') {
    if (!file_exists(APPPATH.'views/pages/titulos/'.$page.'.php')) {
        show_404();
    }
    $data['titles'] = $this->title_model->get_titles();
    $this->load->view('templates/system-header');
    $this->load->view('pages/titulos/titulosCadastrados', $data);
    $this->load->view('templates/system-footer');
}

View

<tbody>
    <tr>  
        <?php foreach ($titles as $title) { ?>
            <tr><?php echo $title->name ?></tr>
        <?php } ?>
    </tr>
</tbody>

Table in the database

CREATE TABLE IF NOT EXISTS tb_titles(
ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(100) NOT NULL,
DESCRIPTION VARCHAR(500),
VALUE DOUBLE NOT NULL,
PAID_OUT_AT TIMESTAMP NOT NULL,
REGISTERED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP(),
UPDATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP()
);

The error presented is:

Message: Trying to get Property of non-object

Filename: titles/titleCartists.php

Line Number: 39

Backtrace:

File: C: Cibraprograms Xampp htdocs financas application views pages titleCadastrados.php Line: 39 Function: _error_handler

Any idea what it might be?

1 answer

2


The problem is in get_titles() you ask to return an array containing other arrays and not an array of objects. The way to access an array is different from accessing an object so the error in the view.

Change:

public function get_titles() {
    $title = $this->db->get('TB_TITLES');
    return $title->result_array(); //retorna um array de arrays
}

To:

public function get_titles() {
    $title = $this->db->get('TB_TITLES');
    return $title->result();
}

Documentation:

Results

  • Thank you @rray, it worked. Just one observation, I had to change the amount I wanted to access (In my case, name) the same way it is in the bank (Everything in uppercase): $title->NAME

  • 1

    @Csorgo in the case of objects the property name must be written in the same way as it was written in the database. If you use arrays instead of objects, you can convert keys with array_change_key_case

Browser other questions tagged

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