Symfony查询出错:预期文字,得到'“'

时间:2015-02-09 09:21:47

标签: php mysql sql symfony select

我有以下查询:

$query = $em->createQueryBuilder()
            ->select('u.id, u.username, u.username_canonical, u.email, u.email_canonical, u.last_login, u.name, u.type, u.phone, u.site, u.agency, u.subtype, u.info, u.created_date, u.vip')
            ->from('ContrateAdminBundle:Fosuser', 'u')
            ->where('u.created_date BETWEEN "'.$fromdateaccounts.'" AND "'.$todateaccounts.'" ')                      
            ->getQuery();

$results = $query->getResult();

在Symfony中获取用户数据,但我收到以下错误:

[Syntax Error] line 0, col 223: Error: Expected Literal, got '"'
500 Internal Server Error - QueryException
1 linked Exception: QueryException »

我的查询输出是:

SELECT u.id, u.username, u.username_canonical, u.email, u.email_canonical, u.last_login, u.name, u.type, u.phone, u.site, u.agency, u.subtype, u.info, u.created_date, u.vip
FROM ContrateAdminBundle:Fosuser u
WHERE u.created_date BETWEEN "2014-08-04 13:29" AND "2014-10-30 13:29" 

3 个答案:

答案 0 :(得分:7)

SQL中的字符串文字用单引号'表示,而不是双引号",因此您必须将"替换为查询中的字符串分隔符'

$query = $em->createQueryBuilder()
            ->select('u.id, u.username, u.username_canonical, u.email, u.email_canonical, u.last_login, u.name, u.type, u.phone, u.site, u.agency, u.subtype, u.info, u.created_date,u.vip')
            ->from('ContrateAdminBundle:Fosuser', 'u')
            ->where('u.created_date BETWEEN \'${fromdateaccounts}\' AND \'{$todateaccounts}\'')                      
            ->getQuery();

答案 1 :(得分:2)

您也可以使用Expr:

$queryBuilder = $em->createQueryBuilder();

...
->where($queryBuilder->expr()->between('u.created_date', $fromdateaccounts, $todateaccounts));

答案 2 :(得分:1)

请使用参数。接受的答案可能会生成SQL注入。

    ->where('u.something = ?1')
    ->setParameter(1, '')