我的 Control-6ren">
gpt4 book ai didi

php - 如何在 codeigniter 中将变量从 View 传递到 Controller

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:06:26 25 4
gpt4 key购买 nike

我想为我从 View 中点击的每个链接传递一个语言 ID 到 Controller 。我的查看代码是

  <?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 } ?>

我的 Controller 是

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);
}

languages数组包含语言id和语言名称

我希望名称在 url 而不是 id 中

网址看起来像这样

http://localhost/mediabox/home/box/12/en

如果我在 url 中发送语言 id,那么它是可见的,否则它在 Controller 中是不可见的。如何在不在 url 中发送的情况下获取 Controller 中每个链接的语言 id

谢谢

最佳答案

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

假设您有 url:http://localhost/mediabox/home/box/en

Controller

<?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);
}

库/私有(private)函数

<?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;
}

语言模型

<?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;
}
}

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

session 存储

<?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);

关于php - 如何在 codeigniter 中将变量从 View 传递到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9821542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com