
本文讲解如何在 CodeIgniter 中正确处理存储为逗号分隔字符串(如 "3,5")的数据库字段,通过 AJAX 实现按单个值(如 3 或 5)模糊匹配并返回对应记录,避免 where() 失效问题。
本文讲解如何在 codeigniter 中正确处理存储为逗号分隔字符串(如 "3,5")的数据库字段,通过 ajax 实现按单个值(如 3 或 5)模糊匹配并返回对应记录,避免 `where()` 失效问题。
在 CodeIgniter 开发中,若将多值(如多个位置 ID)以逗号分隔形式存入单一字段(如 location = '3,5'),直接使用 $this->db->where('location', 3) 将无法匹配——因为数据库会严格比对整个字符串 '3,5' ≠ '3'。此时需改用语义化匹配策略,而非简单等值查询。
✅ 正确方案一:使用 where_in()(仅适用于规范化数据结构)
⚠️ 注意:where_in() 要求 location 字段为独立整数型字段(即每条记录只存一个 location 值)。若当前表结构已固定为逗号分隔字符串,则此方案不适用,需重构表结构(推荐长期方案):
// ✅ 仅当 location 是 INT 类型且单值时有效
$this->db->where_in('location', [$postData['location']]);
但根据你提供的示例数据(location = '3,5'),该字段明显是字符串类型且含多值,因此应采用以下更稳妥的字符串匹配方案。
✅ 正确方案二:使用 SQL 模糊匹配(适配逗号分隔字符串)
在模型方法中,替换原 where() 逻辑为如下四条件组合,确保能准确匹配目标值位于开头、中间或结尾的情形:
public function db_barangGetMaster($postData) {
if (!isset($postData['location']) || !is_numeric($postData['location'])) {
return ['response' => 'invalid location parameter'];
}
$loc = (int)$postData['location']; // 强制转为整数,防注入基础防护
$this->db->select('*');
$this->db->from('tabel_item as a');
// 匹配:'3', '3,%', '%,3', '%,3,%'
$this->db->where("location = '{$loc}'
OR location LIKE '{$loc},%'
OR location LIKE '%,{$loc}'
OR location LIKE '%,{$loc},%'");
$query = $this->db->get()->result();
if ($query) {
$response = [];
foreach ($query as $row) {
$response[] = [
'id' => $row->id,
'name' => $row->name,
'lokasi' => $row->location
];
}
return $response;
} else {
return ['response' => 'not found'];
}
}
? 安全提示:上述写法虽简洁,但拼接 SQL 存在潜在注入风险。生产环境强烈建议改用 Query Binding(绑定参数)方式:
$loc = $postData['location'];
$sql = "location = ? OR location LIKE ? OR location LIKE ? OR location LIKE ?";
$this->db->where($sql, [
$loc,
$loc . ',%',
'%,' . $loc,
'%,' . $loc . ',%'
]);
? 前端 AJAX 调用示例(jQuery)
$.ajax({
url: '/your_controller/get_items',
type: 'POST',
data: { location: 3 },
dataType: 'json',
success: function(res) {
if (res.response && res.response === 'not found') {
console.log('未找到匹配项');
} else {
res.forEach(item => {
console.log(item.name + ' - 位置:' + item.lokasi);
});
}
}
});
⚠️ 重要注意事项
- ❗ 反模式警示:将多值存于单字段违反数据库第一范式(1NF),易导致查询低效、索引失效、难以维护。长期建议拆分为关联表(如
item_locations),实现真正关系型设计。 - ✅ 性能优化:若数据量大,可考虑添加生成列(MySQL 5.7+)或全文索引辅助匹配。
- ?️ 输入校验:务必对
$postData['location']做类型与范围校验,防止恶意输入。
综上,面对逗号分隔字段的模糊查询需求,应放弃 where() 的精确匹配思维,转向基于字符串位置的逻辑判断,并在安全、可维护与性能之间做好权衡。











