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

带[product_code]前缀的QueryString参数提取与SQL查询报错解决

问题解答

是的,这个语法错误完全和[product_code]前缀有关!

错误原因

你直接把包含方括号[的字符串拼进了DQL语句中:

->andWhere("k.product_code = $ids")

DQL解析器会把[当成查询语法的一部分(比如数组或函数的开头),而不是字符串字面量的一部分,所以才会抛出"Expected Literal, got '['"的语法错误。

解决步骤

1. 移除[product_code]前缀

你可以用两种简单的方式去掉这个前缀:

  • 字符串替换法:直接把前缀替换为空字符串
    $rawCode = $ids[0];
    $productCode = str_replace('[product_code]', '', $rawCode);
    
  • 截取法:如果前缀长度固定,直接截取后面的有效部分
    $rawCode = $ids[0];
    $prefix = '[product_code]';
    $productCode = substr($rawCode, strlen($prefix));
    

处理后,$productCode就会变成"1INSAZE",也就是你需要的真实产品编码。

2. 安全执行查询(关键!)

绝对不要直接把变量拼进DQL语句里——这不仅会导致语法问题,还会引发SQL注入风险。正确的做法是使用参数绑定:

$result = $this->createQueryBuilder('k')
    ->andWhere('k.product_code = :productCode')
    ->setParameter('productCode', $productCode)
    ->getQuery()
    ->getResult();

ORM会自动处理字符串的转义,既避免了语法错误,又保证了查询的安全性。

完整示例代码

// 获取并处理原始参数
$ids = $request->query->get('ids', null);
$rawCode = $ids[0];
$productCode = str_replace('[product_code]', '', $rawCode);

// 执行安全查询
$result = $this->createQueryBuilder('k')
    ->andWhere('k.product_code = :productCode')
    ->setParameter('productCode', $productCode)
    ->getQuery()
    ->getResult();

return $result;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:40:06