小编典典

Codeigniter result_array()返回一行

sql

在我的表我有两行,但是当我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;
}

阅读 133

收藏
2021-03-23

共1个答案

小编典典

因为$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; ?>
2021-03-23