Codeigniter result_array() returning one row

前端 未结 1 1602
醉梦人生
醉梦人生 2021-01-07 13:57

In my table I have two rows but when I print_r the $data that this model function is connected to it is only returning the second row in the db why

相关标签:
1条回答
  • 2021-01-07 14:24

    Because $row is the loop variable, it will only hold the data from the last iteration after the loop has exited.

    Do it like this:

    function getAllUsers()
    {
        $rows = array(); //will hold all results
        $query = $this->db->get('users');
    
        foreach($query->result_array() as $row)
        {    
            $rows[] = $row; //add the fetched result to the result array;
        }
    
       return $rows; // returning rows, not row
    }
    

    In your controller:

    $data['users'] = $this->yourModel->getAllUsers();
    $this->load->view('yourView',$data);
    

    In your view

    //in your view, $users is an array. Iterate over it
    
    <?php foreach($users as $user) : ?>
    
    <p> Your first name is <?= $user['fName'] ?> </p>
    
    <?php endforeach; ?>
    
    0 讨论(0)
提交回复
热议问题