Home » Php » php – Error with a Symfony query : Expected Literal, got '"'

php – Error with a Symfony query : Expected Literal, got '"'

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have the following query:

$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();

in Symfony to fetch user data, but I got the following error:

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

My query output is:

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" 
How to&Answers:

String literals in SQL are denoted by single quotes ', not double quotes ", so you have to replace the " as string delimiters in your query by ':

$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();

Answer:

You can also use Expr :

$queryBuilder = $em->createQueryBuilder();

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

Answer:

Please use parameters. Accepted answer could generate SQL injections.

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