首页 文章

数据库查询结果有不同的变量,原因是什么?

提问于
浏览
3

在帖子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
}

在你的控制器中:

$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; ?>

从控制器启动查询并且查询结果在 $data['users'] 中,但在视图中我们正在迭代 $users . 这是为什么?

4 回答

  • 1

    在codeigniter(或者像cakePHP这样的mvc框架)中,我们在Controller中使用键和值构建数组 . 然后将其传递给视图作为变量 .

    所以 $data['users']=array(key=>val) 将转到视图并作为 echo $users['key'] 进行访问 .

    仔细查看控制器中的所有变量键(例如 $data['users'] 这里用户是关键)成为视图中的实际变量(例如 $users ),这就是我们称之为MVC结构的原因 .

  • 2

    如果您在控制器中设置,

    $data['users'] = $this->yourModel->getAllUsers();
    $this->load->view('users',$data);    //first argument will be passed to view as $users
    

    在您的视图中,您将调用about参数

    <?php foreach($users as $user) : ?>
    <p> Your first name is <?= $user['fName'] ?> </p>
    <?php endforeach; ?>
    
  • 1

    只需检查 system/core 中的 loader.php 并找到 "public function view" ,它就会回答您的问题 .

  • 1

    $this->load->view() 功能 accepts 2 arguments ,第二个是可选的 . 第一个参数是 view without extension 的名称 . 第二个参数是 array containing key value pairs . 如果传递第二个参数然后 all keys will be converted into variable names 并且它们将占用该数组中存在的值

相关问题