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

在CodeIgniter中如何为分类记录创建页面并设置href链接?

我来一步步帮你搞定这个问题,这在CodeIgniter开发里是非常常见的场景~

步骤1:修改视图中的分类链接

首先要把视图里的空链接href="#"替换成指向对应分类详情页的动态URL,核心是用分类的唯一标识(比如你的categories表主键,假设是id_cat,如果你的表用的是别的字段名,记得替换)来生成链接。

修改后的视图代码:

<div class="row mb-4">
 <div class="items mr-2 ml-2">
 <?php foreach ($row2->result() as $key=>$data) : ?>
 <a class="text-light listcategory" href="<?=base_url('category/detail/'.$data->id_cat)?>"><span><?=$data->name_cat?></span></a>
 <?php endforeach; ?>
 </div>
</div>

⚠️ 注意:要确保你已经加载了CodeIgniter的URL辅助类——要么在config/autoload.php里把url加入$autoload['helper']数组,要么在控制器的index方法里手动加一句$this->load->helper('url');。

步骤2:在控制器中添加详情页方法

接下来在你的控制器(就是写了index方法的那个控制器,假设叫Category.php)里新增一个detail方法,用来接收分类ID、查询对应数据并渲染详情页:

public function detail($category_id) {
    // 加载模型
    $this->load->model('Model_Category');
    
    // 查询单个分类数据(后面要在模型里加对应方法)
    $category = $this->Model_Category->get_single_category($category_id);
    
    // 如果分类不存在,直接返回404页面
    if (!$category) {
        show_404();
    }
    
    // 把分类数据传给详情视图
    $data['category'] = $category;
    $this->load->view('category_detail.php', $data);
}
步骤3:在模型中添加单分类查询方法

打开你的Model_Category.php,新增一个get_single_category方法,用来根据ID查询单条分类记录:

public function get_single_category($id) {
    // 用row()获取单条记录,而非result()的集合
    return $this->db->get_where('categories', ['id_cat' => $id])->row();
}

这里的id_cat要和你数据库表中的主键字段完全一致,如果你的主键是id,就改成['id' => $id]。

步骤4:创建分类详情视图

新建一个视图文件category_detail.php,用来展示单个分类的具体内容,示例代码如下:

<div class="container mt-5">
    <h1><?=$category->name_cat?></h1>
    <!-- 这里可以添加分类的其他字段,比如描述、创建时间等 -->
    <?php if (!empty($category->description)) : ?>
        <div class="mt-3">
            <p><?=$category->description?></p>
        </div>
    <?php endif; ?>
</div>
额外优化建议
  • 记得在config/config.php里配置好正确的base_url,否则base_url()生成的链接会出问题。
  • 可以给detail方法里的$category_id加个验证,确保是数字,避免非法请求:
    if (!is_numeric($category_id)) {
        show_404();
    }
    
  • 如果你的控制器不是Category,而是其他名字(比如Home),记得把链接里的category改成对应控制器名,比如base_url('home/detail/'.$data->id_cat)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:29:36