如何将ID变量传递给CodeIgniter中的控制器

时间:2016-11-01 00:25:05

标签: php codeigniter

我有一个消息列表,当点击标题时,它会将它们带到另一个视图,在那里他们可以看到扩展的消息。

这是我点击链接的视图。

发布视图。

<a href="<?=base_url();?>index.php?/Message/display<?=$row['id']?>">Link</a>

消息控制器:

class Message extends CI_Controller {

  var $TPL;

  public function __construct()
  {
    parent::__construct();
  }

  private function display()
  {

    $query = $this->db->query("SELECT FROM messages WHERE id = '$id';");

    $this->TPL['message'] = $query->result_array();

    $this->template->show('Message', $this->TPL);

  }

  public function index()
  {

     $this->display();

  }
}

消息视图

    <?$int=0;?>
    <? foreach ($threads as $row) {  ?>
    <div class="row">
      <div class="message">
        <h3><?= $row['title']?></h3>
        <p><?= $row['message']?></p>
        <p><?= $row['member']?></p>
      </div>
    </div>
    <hr>   
    <? $int++;?>      
    <? } ?>

2 个答案:

答案 0 :(得分:2)

这很容易。将代码更改为以下内容

<a href="<?php echo site_url('message/display').'/'.$row['id'];?>">Link</a>

然后将您的display方法更改为公开,并将ID参数发送到

public function display($id){
    $this->db->where('id', $id);
    $query = $this->db->get('messages');
    $this->TPL['message'] = $query->result_array();
    $this->template->show('Message', $this->TPL);
  }

最后删除$int=0&amp;您没有使用此视图文件中的$int++;。现在测试

答案 1 :(得分:0)

更改链接

<a href="<?php echo site_url().'message/display/'.$row['id'];?>">Link</a>

在您的控制器中

public function display() {
$id=$this->uri->segment(3);
if($id==null) {
    redirect('Index');
}
else {
    $this->db->where('id', $id);
    $query = $this->db->get('messages');
    $this->TPL['message'] = $query->result_array();
    $this->template->show('Message', $this->TPL);
  }
}
相关问题