0

在我的表中,我有两行,但是当我连接print_r$data这个模型函数时,它只返回数据库中的第二行,为什么?

型号功能:

function getAllUsers()
{
    $query = $this->db->get('users');

    foreach($query->result_array() as $row)
    {
        $row['id'];
        $row['fName'];
        $row['lName'];
        $row['email'];
        $row['password'];
    }

    return $row;
}
4

1 回答 1

4

因为$row是循环变量,所以它只会在循环退出后保存上次迭代的数据。

像这样做:

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
}

在您的控制器中:

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

在你看来

//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; ?>
于 2012-06-14T03:41:21.023 回答