在codeigniter中检索数据:传递变量但未识别

时间:2015-01-14 07:57:36

标签: php codeigniter variables

我是PHP和codeigniter的新手,我遇到了很多PHP错误,例如Invalid argument supplied for foreach()Undefined variable: row and query。在我的观点中,我尝试将其作为(query->results() as $row)并将错误课程预告为1,即undefined varaiable: query

我不确定我缺少哪个部分,我已经在我的模型中声明了查询,似乎控制器无法接收传递的变量。谁能纠正我的错误?并会给出一个解释,以避免将来出现这种错误。谢谢!

模特功能:

function getStudentInfo()
    {
          $this->db->select("firstname,middlename,lastname");
          $this->db->from('studentinfo');
          $query = $this->db->get();
          return $query->result();
    }

控制器功能:

public function index() 
   {
          $this->data['query'] = $this->m_login->getStudentInfo(); //i passed the query to the data variable
          $this->load->view('v_home', $this->data);
   }

查看:

 <!DOCTYPE html>
 <head>
   <title>Simple Login with CodeIgniter - Private Area</title>
 </head>
 <body>
   <h1>Home</h1>
   <h2>Welcome <?php echo $studentid; ?>!</h2>
   <a href="c_home/logout">Logout</a>

 <h4>Display Records From Database Using Codeigniter</h4>
    <table>
     <tr>
      <td><strong>First Name</strong></td>
      <td><strong>Last Name</strong></td>
    </tr>
     <?php foreach($query as $row){?>
     <tr>
         <td><?php echo $row->firstname;?></td>
         <td><?php echo $row->lastname;?></td>
      </tr>    
     <?php }?>  
   </table>


 </body>
</html> 

1 个答案:

答案 0 :(得分:1)

你的程序似乎没问题 您犯了以下错误。

<?php foreach($query as $row);?>//your foreach ends here for this comma
   //those lines are out of foreach
     <?php echo $row->firstname;?>//$row is undefined and $row->firstname is invalid property
     <?php echo $row->lastname;?>//same for lastname

 <?php ?>  

用这种方式。

<?php foreach($query as $row){?>

     <?php echo $row->firstname;?>
     <?php echo $row->lastname;?>

 <?php } ?>