You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在CodeIgniter中如何将URL参数值传递给模型以构建查询?

嘿,入门CodeIgniter的时候碰到这类问题太常见啦!你想通过URL里的参数值在模型里构建查询,先看看你现有的代码,咱们再一步步完善它~

你的现有代码

控制器(Customer.php)

public function customer_edit($id) { 
    $this->load->model( 'Customers_model' ); //加载模型 
    $data[ 'results' ] = $this->Customers_model->edit_customers($id); 
    $this->load->view( 'customers/customer_edit', $data ); 
}

模型(customers_model.php)

public function edit_customers($id)
//该函数返回一个查询结果的内容
完善建议

你现在的模型函数还没实现具体的查询逻辑,这里推荐用CodeIgniter自带的查询构造器来写,既安全(自动防止SQL注入)又符合框架的最佳实践:

public function edit_customers($id) {
    // 假设你的客户表名叫`customers`,主键字段是`id`
    // get_where方法会自动帮你处理参数转义,避免安全问题
    $query = $this->db->get_where('customers', ['id' => $id]);
    
    // 返回单条记录的对象形式,适合在视图里用$results->字段名来调用
    return $query->row();
    
    // 如果更习惯用数组形式,换成下面这行:
    // return $query->row_array();
}

这样一来,控制器里的逻辑是没问题的,URL里传入的$id会被正确传到模型,模型通过查询构造器获取对应ID的客户数据,最后传给视图渲染就行啦~

内容的提问来源于stack exchange,提问作者phishyman2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:14:51