【问题标题】:CodeIgniter 3.1.4 - PHP foreach not working the way I intend for $row elementsCodeIgniter 3.1.4 - PHP foreach 无法按照我对 $row 元素的预期方式工作
【发布时间】:2026-01-10 20:15:02
【问题描述】:

我想要做的是使用 PHP foreach 将所有用户和与他们相关的数据的列表附加到表行,该信息是从数据库中获取的。我遇到的问题是以下错误:

[严重性:错误消息:调用数组上的成员函数 result_array()]

我阅读了similar question 关于此的内容,但它似乎无法解决我的问题,因为当我从模型或控制器。

这是 User.php 模型:

Class User extends CI_Model
{
    function populateUsers()
    {
        $this->db->select('username, accessLevel, fullName');
        $this->db->from('users');

        $userquery = $this->db->get();

        if($userquery -> num_rows()>=1)
        {
            return $userquery->result_array();
        }
        else
        {
            return false;
        }

    }

}

这是来自 AdminCP.php 控制器的 sn-p:

    public function index()
    {   
    $this->load->helper(array('form')); // for user creation
    $session_data = $this->session->userdata('logged_in');
    $aLevel = $session_data['accessLevel'];
    if($this->session->userdata('logged_in') && $aLevel == 'Admin')
    {                   
        $userResult = $this->user->populateUsers();
        if($userResult)
        {
            $user_array = array();
            foreach($userResult as $row)
            {
                $user_array = array(
                'username' => $row->username,
                'accessLevel' => $row->accessLevel,
                'fullName' => $row->fullName
                );

                $data['accessLevel'] = $session_data['accessLevel'];                
                $data['username'] = $session_data['username'];          
                $data['fullName'] = $session_data['fullName'];
                $data['userList'] = $user_array;                
                $this->load->view('admin_cp_view', $data);
            }
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }   
    else
    {
    redirect('home', 'refresh');            
    session_write_close();
    }
}

最后,这是 Admin_CP_View.php 页面的部分,我想在其上显示此信息:

<div class="well">
<h4>Manage users</h4>
<p>Select a user from the list to manage</p>
<table class="table">                           
                    <thead>                         
                            <tr>
                                <th>Username</th>
                                <th>Access Level</th>
                                <th>Full Name</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($userList->result_array() as $row)
                        { ?>
                            <tr>
                                <td><?php echo $row['username'];?></td>
                                <td><?php echo $row['accessLevel'];?></td>
                                <td><?php echo $row['fullName'];?></td>                                 
                            </tr>
                        <?php } ?>

                        </tbody>
                    </table>
                </div>

请告诉我这里哪里出错了,谢谢!

【问题讨论】:

    标签: php mysql arrays codeigniter


    【解决方案1】:

    你有几个问题。首先,与其说是一个问题,不如说它是毫无价值的代码。控制器不需要返回值,因为 Codeigniter 不期望返回值,并且无论如何都不会关注它。

    其次,我已从 index 中删除了这些行,因为它们在视图中似乎未使用。

    $data['accessLevel'] = $session_data['accessLevel'];
    $data['username'] = $session_data['username'];
    $data['fullName'] = $session_data['fullName'];
    

    这是一个修改后的控制器索引函数,删除了返回 TRUE 或 FALSE 的逻辑。

    public function index()
    {
      $this->load->helper(array('form')); // for user creation
      $session_data = $this->session->userdata('logged_in');
      $aLevel = $session_data['accessLevel'];
      if($this->session->userdata('logged_in') && $aLevel == 'Admin')
      {
        $data['userList'] = $this->user->populateUsers();
        $this->load->view('admin_cp_view', $data);
      }
      else
      {
        session_write_close();
        redirect('home', 'refresh');
      }
    }
    

    我会以不同的方式对模型的populateUsers 方法进行编码。首先不要盲目使用查询生成器。在某些情况下,它是一个很棒的工具。但是你的 sql 太简单了,没有必要为这样一个超级简单的数据库请求运行大量的 Query Build 代码。

    查看代码 cmets 以了解“为什么?”关于其他变化。

    Class User extends CI_Model
    {
      function populateUsers()
      {
        $userquery = $this->db->query("Select usernam, accessLevel, fullName from users");
    
        if($userquery->num_rows() > 0)
        {
          return $userquery->result_array();
        }
      //{
        //else
        //you do not need the else because if there were rows the method has returned 
        //and the next line will never be executed. 
    
        //On the other hand, if there are no rows then this line WILL execute
        return array(); //Return empty array so that the view won't try to run foreach on a boolean
    //  }
      }
    

    然后在视图中您的&lt;table&gt; 的代码是这样的

    <table class="table">                           
      <thead>                         
        <tr>
          <th>Username</th>
          <th>Access Level</th>
          <th>Full Name</th>
        </tr>
      </thead>
      <tbody>
        <?php
        foreach($userList as $row) { ?>
        <tr>
          <td><?php echo $row['username']; ?></td>
          <td><?php echo $row['accessLevel']; ?></td>
          <td><?php echo $row['fullName']; ?></td>                                 
        </tr>
        <?php } ?>
      </tbody>
    </table>
    

    这将为$userList 中的每个项目在表中写入一行。

    我认为您可能没有正确做出我在第一次尝试回答时建议的更改。您可能会加载多个页面,因为您在 foreach 循环内调用了 load-&gt;view。现在只有表格行应该重复。

    【讨论】:

    • 感谢您的帮助,但它仍然无法正常工作,实际上会导致页面不断重复从数据库中检索到的不同行:(prntscr.com/esbril)。它基本上不是将数据附加到一行,而是实际上看起来像是在生成一个全新的页面。
    • 我很难想象您所描述的内容,并且您链接到的屏幕截图没有显示任何异常。
    • 啊,是的,我应该更清楚。基本上,对于 foreach 检索的每条记录,它会将其作为一个完整的其他页面附加,但在“其他”页面上的该表上显示不同的值行。这是另一个屏幕截图,应该澄清我的意思:prntscr.com/esehi1(请注意,我手动将其缩小以便您可以看到)
    • 我已经完全重写了我的答案。希望对您有所帮助。
    • 完美!感谢您对此的耐心等待,它现在按预期工作!
    【解决方案2】:

    在您的 AdminCP.php 中编辑

     public function index()
        {   
        $this->load->helper(array('form')); // for user creation
        $session_data = $this->session->userdata('logged_in');
        $aLevel = $session_data['accessLevel'];
        if($this->session->userdata('logged_in') && $aLevel == 'Admin')
        {                   
            $userResult = $this->user->populateUsers();
            if($userResult)
            {
    
                    $this->load->view('admin_cp_view', $userResult);
                }
                return TRUE;
            }
            else
            {
                return FALSE;
            }
        }   
        else
        {
        redirect('home', 'refresh');            
        session_write_close();
        }
    }
    

    在您的 Admin_CP_View.php 中编辑

    <div class="well">
    <h4>Manage users</h4>
    <p>Select a user from the list to manage</p>
    <table class="table">                           
                        <thead>                         
                                <tr>
                                    <th>Username</th>
                                    <th>Access Level</th>
                                    <th>Full Name</th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($userResult as $row)
                            { ?>
                                <tr>
                                    <td><?php echo $row['username'];?></td>
                                    <td><?php echo $row['accessLevel'];?></td>
                                    <td><?php echo $row['fullName'];?></td>                                 
                                </tr>
                            <?php } ?>
    
                            </tbody>
                        </table>
                    </div>
    

    这可能会对你有所帮助.. 谢谢!

    【讨论】:

      【解决方案3】:

      将您的用户模型更改为:

      Class User extends CI_Model
      {
          function populateUsers()
          {
              $this->db->select('username, accessLevel, fullName');
              $this->db->from('users');
      
              $userquery = $this->db->get();
      
              if($userquery->num_rows() >= 1)
              {
                  return $userquery->result();
              }
              else
              {
                  return false;
              }
      
          }
      
      }
      

      【讨论】: