如何在codeigniter中将变量从视图传递给控制器

Far*_*han 5 php codeigniter

我想将我从视图中单击的每个链接的语言 ID 传递给控制器​​。我的视图代码是

  <?php foreach ($languages as $lang) { ?>
     <li>
       <a href="<?php echo base_url(); ?>home/box/<?php echo $template_data['box_id']?>/<?php echo $lang['language_name']?>"></a>
     </li>
   <?php } ?> 
Run Code Online (Sandbox Code Playgroud)

我的控制器是

public function box($box_id=null, $language_name=null, $language_id=null) {
   /// my function code
        echo $box_id;
        echo $language_name;
        echo $language_id;
   $data['languages'] = $this->Home_model->getLanguages($box_id);
  }
Run Code Online (Sandbox Code Playgroud)

语言数组包含语言 ID 和语言名称

我希望名称在 url 中,但不是 id

网址看起来像这样

http://localhost/mediabox/home/box/12/en
Run Code Online (Sandbox Code Playgroud)

如果我在 url 中发送语言 ID,则它是可见的,否则它在控制器中不可见。如何获取控制器中每个链接的语言 ID 而不在 url 中发送它

谢谢

gor*_*ive 5

在没有 ID 的 url 中传递语言名称,与表中的 languag_name 列进行比较。

让我们假设你有网址: http://localhost/mediabox/home/box/en

控制器

<?php
# I wont write a controller but you should know how to do that, im also writing code as if you are just focusing on getting language.
public function box( /**pass in your other uri params as needed **/ $lang_name = 'en'){
  #you could load this in the constructor so you dont have to load it each time, or in autoload.php if your using it site wide.
  $this->load->model('lang_model', 'langModel');

  #this example shows loading the library and running the function
  $this->load->library('lang_library');
  $this->lang_library->_getLang($lang);

  #this example shows putting the getLang function inside the controller itsself.
  self::_getLang($lang);
}
Run Code Online (Sandbox Code Playgroud)

图书馆/私人功能

<?php
private functon _getLang($lang = 'en'){
  #run the query to retrieve the lang based on the lang_name, returns object of lang incl id
  $lang = $this->langModel->getLang($lang_name);
  if (!$lang){
    die('language not found');
  }else{
    return $lang;
  }
Run Code Online (Sandbox Code Playgroud)

语言模型

<?php
public function getLang($lang_name = 'en'){
  $this->db->where('lang_name', $lang_name);
  $this->db->limit(1);
  $q = $this->db->get('languages');

  if ($q->mysql_num_rows > 0){
    return $q->result();
  }else{
    return false;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,您将拥有一个与对象关联的变量,然后您可以简单地调用$lang->lang_name;$lang->lang_id;

会话存储

<?php
#you could call this in the beginning after using an ajax `$.post();` to retrieve the ID.. the easiest route though is whats above. I use this in my REST APIs
$this->session->set_userdata('lang', $lang);
Run Code Online (Sandbox Code Playgroud)