无法调用从控制器获取数据以在codeigniter中查看

时间:2018-04-17 12:37:27

标签: php codeigniter

我无法使用CodeIgniter中的控制器和模型显示数据库中的数据。

控制器代码:

class Leads extends CI_Controller {


   public function show($id) {

   $this->load->model('leads_model');

   $leads = $this->leads_model->get_leads($id);

   $data['name'] = $leads['name'];

   $data['email'] = $leads['email'];

   $data['contact'] = $leads['contact'];

   $data['referral'] = $leads['referral'];

   $data['project_detail'] = $leads['project_detail'];

   $data['note'] = $leads['note'];

   $this->load->view('layouts/header', $data);

   $this->load->view('layouts/sidebar', $data);

   $this->load->view('pages/leads', $data);

   $this->load->view('layouts/footer', $data);


}

型号代码:

class Leads_model extends CI_Model {


public function __construct() {

    $this -> load -> database();

}
public function get_leads($id) {

    if ($id != FALSE) {

        $query = $this -> db -> get('leads', array('lead_id' => $id));
        return $query -> row_array();

    }

    else {

        return FALSE;

    }

}

查看代码:

<td>
    <?php echo $data['name']; ?>
</td>
<td>
    <?php echo $data['email']; ?>
</td>
<td>
    <?php echo $data['contact']; ?>
</td>
<td>
    <?php echo $data['referral']; ?>
</td>
<td>
    <?php echo $data['project_detail']; ?>
</td>
<td>
    <?php echo $data['note']; ?>
</td>

1 个答案:

答案 0 :(得分:0)

$leadsarray,因此视图中应该有foreach循环

在控制器中:

public function show($id) 
{
  $this->load->model('leads_model');
  $leads = $this->leads_model->get_leads($id);
  $data['leads'] = $leads;
  $this->load->view('layouts/header', $data);

  $this->load->view('layouts/sidebar', $data);

  $this->load->view('pages/leads', $data);
}

你的模特:

public function get_leads($id) {
    if ($id != FALSE) {
        $this->db->where(array('lead_id' => $id));
        $query = $this->db->get('leads');
        return $query->row_array();
    }
    else {
        return FALSE;
    }
}

您的观点应该是这样的:

 <?php if ($leads) {
      foreach($leads as $lead) {?>
         <?php echo $lead['name']; ?>  
         <?php echo $lead['email']; ?>  
         <?php echo $lead['contact']; ?>  
         <?php echo $lead['referral']; ?>  
         <?php echo $lead['project_details']; ?>  
         <?php echo $lead['note']; ?>  
      }
  }?>

如果单行数据:在视图中使用不带$data的变量

如果您的模型方法返回$query->row();

您的观点:

 <td><?php echo $name; ?></td>
 <td><?php echo $email; ?></td>
 <td><?php echo $contact; ?></td>
 <td><?php echo $referral; ?></td>
 <td><?php echo $project_detail; ?></td>
 <td><?php echo $note; ?></td>

了解更多:https://www.codeigniter.com/user_guide/database/query_builder.html