Search code examples
symfonydoctrinedoctrine-ormdql

Symfony2 repository query not working


I am developing an application using Symfony2 and DQL for building some queries in the repositories. I have the next code in the controller:

$emGalPak = $this->getDoctrine()->getEntityManager();
  $OsatugabeKop = $emGalPak->getRepository('AnotatzaileaAnotatzaileaBundle:GalderaPaketea')
                             ->getOsatugabeKop(); 

and this is the query I built in the repository corresponding to the entity mentioned above:

<?php

namespace Anotatzailea\AnotatzaileaBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * GalderaPaketeaRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class GalderaPaketeaRepository extends EntityRepository
{
    public function getOsatugabeKop()
    {
        $qb = $this->createQueryBuilder('c')
                   ->select('c')
                   ->where('c.Osatua = 0')
        $Emaitza = $qb->getQuery()->getResult();

                return sizeof($Emaitza);

    }

}

When running the code it shows the next error:

Parse error: syntax error, unexpected T_VARIABLE in /var/www/Symfony/src/Anotatzailea/AnotatzaileaBundle/Repository/GalderaPaketeaRepository.php on line 20

Any idea on how I can solve this error?


Solution

  • This has nothing to do with your query not working.

    When you see a "Parse error" that means your PHP code itself is improperly formatted and the PHP engine cannot even parse it, let alone run it.

    In this particular case, you're missing a semicolon at the end of your expression creating the query builder.

    public function getOsatugabeKop()
    {
        $qb = $this->createQueryBuilder('c')
                   ->select('c')
                   ->where('c.Osatua = 0'); // <--- right there
        $Emaitza = $qb->getQuery()->getResult();
    
        return sizeof($Emaitza);
    }
    

    When you get the unexpected T_VARIABLE error that's almost always because you omitted a semicolon and the parser encountered a variable before it thought it should. It's easier to see the mistake if you take out the whitespace.

    // Bad Code, two lines
    $now = time()
    $one = 1;
    
    // Bad Code, one line
    $now = time()$one = 1;
    // ----------^  Pretty obvious now that a semicolon is missing
    // And that a variable was encountered unexpectedly
    

    Cheers