php - 数据库查询结果来自不同的变量,原因是什么?

标签 php mysql codeigniter

在帖子中Codeigniter result_array() returning one row https://stackoverflow.com/users/315828/xbonez答案是这样的

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
}

在你的 Controller 中:

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

在你看来

//在你看来,$users是一个数组。遍历它

<?php foreach($users as $user) : ?>

<p> Your first name is <?= $user['fName'] ?> </p>

<?php endforeach; ?>

从 Controller 发起查询,查询结果在 $data['users'] 中,但在 View 中我们正在迭代为 $users。这是为什么?

最佳答案

$this->load->view() 函数接受两个参数,第二个是可选的。第一个参数是 没有扩展名的 View 的名称。第二个参数是包含键值对的数组。如果传递了第二个参数,则 所有键都将转换为变量名,并且它们将占据该数组中存在的值

关于php - 数据库查询结果来自不同的变量,原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32065152/

相关文章:

javascript - jQuery,如何使点击函数与数组一起使用以根据 id 切换 div?

javascript - 无法使用 session 变量来存储数据

php - 如何在 mysql 中查找 Sage 50 Database v22 中的关系(已转换为 mysql)

php - 教义查询生成器〜日期时间

javascript - 在codeigniter中使用javascript将组合框添加到html

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

mysql - 从空的配置单元表传递增量值

php - 验证数据库中是否存在输入的用于请求密码的电子邮件

php - Controller (php)错误。这是什么意思?

javascript - 如何在 JQuery 中重复相同的代码,并为每个代码附加不同的编号?