Reputation: 4650
I'm trying to execute a simple query, but I can't understand where is my mistake. Please help!
This is in the repository class:
public function searchFriends ($param)
{
return $this->getEntityManager()
->createQuery('SELECT f FROM EMMyFriendsBundle:Friend f WHERE f.name='.$param)
->getResult();
}
And this is how I call it from the controller's action:
$em = $this->getDoctrine()->getEntityManager();
$result = $em->getRepository('EMMyFriendsBundle:Friend')
->searchFriends($search->getWords());
When it's in this way, I get the following error:
[Semantical Error] line 0, col 54 near 'Maria': Error: 'Maria' is not defined.
500 Internal Server Error - QueryException
I tried to put the searched value in quotes in this way:
public function searchFriends ($param)
{
return $this->getEntityManager()
->createQuery('SELECT f FROM EMMyFriendsBundle:Friend f WHERE f.name=" '.$param ' " ')
->getResult();
}
but then I get
[Syntax Error] line 0, col 59: Error: Expected end of string, got ' " '
500 Internal Server Error - QueryException
Could you please tell me how to write the query correctly? Thanks in advance!
EDIT
I also tried this:
public function searchFriends ($param)
{
$q = $this
->createQueryBuilder('f')
->where('f.name = :name')
->setParameter('name', $param)
->getQuery();
return $q->getResult();
}
with this:
$em = $this->getDoctrine()->getEntityManager();
$result = $em->getRepository('EMMyFriendsBundle:Friend')
->searchFriends($search->getWords());
and it's workiiing
Upvotes: 0
Views: 12362
Reputation: 1542
You need to use the literal expression:
public function searchFriends($param)
{
$qb = $this->createQueryBuilder('f')
->where($qb->expr()->eq('f.name', $qb->expr()->literal($param)));
return $qb->getQuery()->getResult();
}
Upvotes: 1
Reputation: 1330
Although I wouldn't use this way of passing parameters to a query (check this), your mistake is in the way you built the string that lacks a dot. It should be like this:
public function searchFriends ($param)
{
return $this->getEntityManager()
->createQuery('SELECT f FROM EMMyFriendsBundle:Friend f WHERE f.name="'.$param.'"')
->getResult();
}
Upvotes: 2