0
votes

i want to passing data from model to controller then to view this code explain it.

the model

public function get_all_college_name() {
    $q = $this -> db -> query('select * from college');
    if ($q -> num_rows() > 0) {
        foreach ($q->result() as $row) {
            $data[] = $row;
        }
        return $data;
    }
}

the controller code

public function index() {
    $this -> load -> model('retriver_data');
    $data['rows'] = $this -> retriver_data -> get_all_college_name();

    $this -> load -> view('home', $data);

    //$this -> view_something('home', $data);
}

the view code

<body>
    <?php
    foreach ($rows as $r) {
        echo $r -> name;
    }
    ?>
</body>

the error appears

A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/home.php

Line Number: 8

1
Where is $rows defined? - Sterling Archer
@RUJordan $data['rows'] is the query working ? Also make sure you return an empty array if query fails - exussum
do var_dump($data) before sending to view probably it is not correct format - Biswajit Maji
$rows defined in controller - Jihad Mahfouz
@user1281385 how i do it? - Jihad Mahfouz

1 Answers

0
votes

For CI, in my models I usually use:

if ($query->num_rows() == 0)
    return FALSE;

return $query->result_array();

then if your view you'll check if the array is false before displaying

<body>
    <?php if ( ! $rows) : ?>
        no data
    <?php else: ?>
        <?php foreach ($rows as $row): ?>
            <?php print $row->name; ?>
        <?php endforeach;?>
    <?php endif; ?>
</body>