Hi I'm using PHP Silex with Doctrine DBAL query builder (no ORM) and SQLite. It sort of works, so I can build a query and it spits back results, but I for the life of me I can't get setting parameters to work (I get empty array all the time).
Here's what works:
$qb->select('*')
->from('photos')
->where("country = '".$country."'")
->andWhere('status = 1')
->orderBy($sort[0], $sort[1])
->setFirstResult($start)
->setMaxResults($limit)
For obvious reasons I would like to replace that with:
$qb->select('*')
->from('photos')
->where("country = ?") /// <--
->andWhere('status = 1')
->orderBy($sort[0], $sort[1])
->setFirstResult($start)
->setMaxResults($limit)
->setParameter(0, $country) /// <--
Or:
$qb->select('*')
->from('photos')
->where("country = :country") /// <--
->andWhere('status = 1')
->orderBy($sort[0], $sort[1])
->setFirstResult($start)
->setMaxResults($limit)
->setParameter(':country', $country) /// <--
Or even:
$qb = $this->db->createQueryBuilder();
$expr = $qb->expr();
$qb->select('*')
->from('photos')
->where($qb->expr()->andX(
$qb->expr()->eq('country', '?1'), /// <--
$qb->expr()->eq('status', 1)
))
->orderBy($sort[0], $sort[1])
->setFirstResult($start)
->setMaxResults($limit)
->setParameter(1, $country) /// <--
These are all examples of setting params I found in the docs, however none of them seems to work and I'm not sure how to debug that. Checking $qb->getSQL() and $qb->getParams() doesn't seem to show anything useful.
Im using ("doctrine/dbal": "~2.2") if that matters.
I came back to my own question by accident cause I solved it long time ago and of course it turned out to be a silly thing. The problem lied not in building the query properly but using it the right way. Here's the answer for future reference.
With Query Builder you don't do:
$this->db->fetchAll($qb->getSQL());
// you get query with unfilled placeholders
but rather:
$qb->execute()->fetchAll();
Thanks to all who tried to help!
Related
In my symfony project I have two entities that are related via one to many.
I need to find the first and last child, so I use repository functions that look like this:
public function getFirstPost(Topic $topic)
{
$query = $this->createQueryBuilder('t')
->addSelect('p')
->join('t.posts', 'p')
->where('t.id = :topic_id')
->setParameter('topic_id' => $topic->getId())
->orderBy('p.id', 'ASC')
->setMaxResults(1)
->getQuery();
return $query->getOneOrNullResult();
}
public function getLastPost(Topic $topic)
{
$query = $this->createQueryBuilder('t')
->addSelect('p')
->join('t.posts', 'p')
->where('t.id = :topic_id')
->setParameter('topic_id' => $topic->getId())
->orderBy('p.id', 'DESC')
->setMaxResults(1)
->getQuery();
return $query->getOneOrNullResult();
}
So the only difference is in in ->orderBy(), for the first Post I use ASC and for the last I use DESC.
Now If I use one of those functions from my controller, the return the expected result and work just fine. But If I run them both at the same time from my controller, they return the same result, which they shouldn't.
My guess is that Doctrine caches these queries and the results somehow and that's why the return the same so I tried using $query->useResultCache(false) but that didn't do anything.
So my question is, why is this happening and how can I fix it?
Well, it is cache issue indeed, but mostly it is query issue. Instead of returning a post in these function you return the whole topic with joined posts.
What you can do is to rewrite these queries to select Post entity directly and join Topic entity to it which will be filtered by.
If you really(dont do this) need these queries to work you can detach first topic returned by one of those methods and then call the other method:
$this->getDoctrine()->getManager()->detach($firstTopic);
Below is the code excerpt I have
$column_name = "ipAddress";
$qb = EntityManagerContainer::get()->createQueryBuilder();
$qb->select('u')
->from(BlacklistedIps::class, 'u');
if($search_term)
{
$clause = $qb->expr()->like("u.".$column_name, "'%$search_term%'");
$qb->where($clause);
}
$query = $qb->getQuery();
$result = $query->getResult();
It works absolutely fine (although it's open to SQL injection but that's another story).
My problem with this is the need to have "'%$search_term%'". Without this extra set of single quotes the query fails
Uncaught exception 'Doctrine\ORM\Query\QueryException' with message
'SELECT u FROM Orm\Entity\BlacklistedIps u WHERE u.ipAddress LIKE
%123% ORDER BY u.reason desc' in ***
I am not entirely sure I am doing it the right way. Because if I do, then there is a bug (mssing feature?) in Doctrine2. When I do
$qb->expr()->like("u.".$column_name, "%$search_term%");
then I am ABSOLUTELY sure that I am dealing with a string. When integers or booleans or floats, etc are compared to each other different operators are used, but definitely not LIKE. LIKE is used ONLY when dealing with strings, so quoting the string in DQL is exactly the only possible ->like method use case.
Please tell me I am doing something wrong. I've been using Doctrine2 for couple of days only and feel fascinated by it. But don't like strings not being quoted automatically for me.
it looks like a problem of how you use querybuilder. You should do something like that :
$qb ->where($qb->expr()->orX($qb->expr()->like('u.'.$column_name, $qb->expr()->literal("%$searchTerm%"))))
or
$qb->where($qb->expr()->like("u.".$column_name, array("%$searchTerm%")));
also to avoid sql injection, a good practice is to not pass user input in any querybuilder methods, use setParameter with ? or : instead.
$qb->where('u.'.$column_name.' LIKE :searchTerm')
$qb->setParameter('searchTerm', '%'.$searchTerm.'%')
or something like :
$qb->expr()->like('u.'.$column_name, '?1')
$qb->getQuery()->setParameter(1, '%' . $searchTerm . '%');
Notice the following:
how I've broken the query up for increased security of your database.
my use of "andWhere" throughout the query being built
how I've assigned the value of the executed query to $result
public function findPending($id)
{
$qb = $this->createQueryBuilder('o')
->addSelect('s')
->leftJoin('MyApp\\Model\\Entity\\Shipment', 's')
->orderBy('o.date_sent', 'DESC');
// Order has been sent and was not cancelled
$qb
->andWhere($qb->expr()->andX(
$qb->expr()->eq('o.date_cancelled','0000-00-00 00:00:00'),
$qb->expr()->neq('o.date_sent','0000-00-00 00:00:00')
));
$qb
->andWhere($qb->expr()->orX(
// Order doesn't have a shipment
$qb->expr()->isNull('s.order'),
// OR Order has a shipment
$qb->expr()->orX(
// Shipment has not been sent
$qb->expr()->eq('s.date_sent','0000-00-00 00:00:00'),
// OR Shipment has been sent AND it was cancelled
$qb->expr()->andX(
$qb->expr()->neq('s.date_sent','0000-00-00 00:00:00'),
$qb->expr()->eq('s.date_cancelled','0000-00-00 00:00:00')
)
)
));
$qb
->setMaxResults(6);
$result = $qb->getQuery()
->getResult();
return $result;
}
To see the query you've created add this before "$result"
$qb->getQuery():
Before I begin, I believe I have tried everything from this previous post: How to use WHERE IN with Doctrine 2
So I have a Silex application connected to a MySQL DB using Doctrine via composer (doctrine/dbal 2.2.*)
The query builder I am trying to run is this:
$qb = $this->db->createQueryBuilder();
$stmt = $qb->select('DAY(datefield1) x, COUNT(*) value')
->from('table1', 's')
->join('s', 'table2', 't', 't.key=s.key')
->where('MONTH(datefield1) = :billMonth')
->andWhere('YEAR(datefield1) = :billYear')
->andWhere('t.key IN (:keylist)')
->groupBy('x')
->orderBy('x', 'asc')
->setParameter(':billMonth', $month)
->setParameter(':billYear', $year)
->setParameter(':keylist', implode(",", $keylist))
->execute();
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
The parameters are (month=8)(year=2014)(keylist=array(1,2,3,4))
The query does not fail but it curiously doesn't contain all the data that it should.
I have tried ->setParameter(':keylist', $keylist) to use the raw array, and this didn't work.
I have tried this kind of syntax too:
$qb->add('where', $qb->expr()->in('r.winner', array('?1')));
However that threw up an error because the in method wasn't available in expression builder class.
Please will someone cast an eye over this and save me from having to hardcode my SQL?
OK seeing as this old thread has seen some action since I last looked I wanted to confirm that the issue is long resolved - a third parameter in setParameter allows you to inform Doctrine how to handle the array:
$qb = $this->db->createQueryBuilder();
$stmt = $qb
->select('*')
->from(self::DB_TABLE, 'x')
->where('x.service IN (:services)')
->orderBy('x.session_end', 'DESC')
->addOrderBy('x.direction', 'DESC')
->setParameter(':services', $services, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
->setFirstResult($offset)
->setMaxResults($count)
->execute();
$result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
DB placeholders/parameters are for single values. You're passing in a monolithic string 1,2,3,4 due to calling implode() on the array. Given:
WHERE t.key IN (:keylist)
then this query will be executed as the equivalent of
WHERE t.key IN ('1,2,3,4')
^-------^---note the quotes
Since it's a string, and only one single string in the IN clause, it's the functional equivalent of
WHERE t.key = '1,2,3,4'
and not the
WHERE (t.key = 1 OR t.key = 2 OR ....)
you want it to be. Either set up multiple parameters, one for each value in your array, or embed your string in the query directly
->andWhere('t.key IN (' . implode(',', $keylist) . ')')
which of course opens you up to sql injection attack vulnerabilities.
If you build the sql query yourself you can use DBAL's PARAM_INT_ARRAY type:
use Doctrine\DBAL\Connection as DB;
$db->executeQuery('SELECT DAY(datefield1) x, COUNT(*) value
FROM table1 s
JOIN table2 t ON t.key=s.key
WHERE MONTH(datefield1) = :billMonth
AND YEAR(datefield1) = :billYear
AND t.key IN (:keylist)
GROUP BY x
ORDER BY x ASC',
array(':billMonth' => $month, ':billYear' => $year, ':keylist' => $keylist),
array(':billMonth' => \PDO::PARAM_INT, ':billYear' => \PDO::PARAM_INT, ':keylist' => DB::PARAM_INT_ARRAY
)->fetchAll(\PDO::FETCH_ASSOC);
Correct way to handle such IN clause is as simple as it can be:
$qb = $this->db->createQueryBuilder();
$stmt = $qb->(...)
->andWhere('t.key IN (:keylist)')
->setParameter(':keylist', $keylist)
->getQuery()
->getArrayResult();
I have used this dozen times and it works - doctrine is smart enough to handle your $keylist being array.
Other thing is that I don't know why you're using fetchAll method which is reduntant here - execute() is just enough. Maybe this is a root of your problem.
My suggestion: try to fire action in dev mode (app_dev.php) and check your app/logs/dev.log - you will find all sql queries performed. Verify that database returns data which you are expecting from Doctrine.
->add('where', $qb->expr()->andX(
$qb->expr()->in('r.winner', ':winner')
))
->setParameters(array(
"winner" => $winners,
"billMonth", $month,
// add all params here
));
You should use the in expression via the querybuilder like below, and change how you set the parameter:
->andWhere($qb->expr()->in('t.key', ':keylist'))
The complete code:
$qb = $this->db->createQueryBuilder();
$stmt = $qb->select('DAY(datefield1) x, COUNT(*) value')
->from('table1', 's')
->join('s', 'table2', 't', 't.key=s.key')
->where('MONTH(datefield1) = :billMonth')
->andWhere('YEAR(datefield1) = :billYear')
->andWhere('t.key')
->andWhere($qb->expr()->in('t.key', ':keylist'))
->groupBy('x')
->orderBy('x', 'asc')
->setParameter(':billMonth', $month)
->setParameter(':billYear', $year)
->setParameter(':keylist', $keylist)
->execute();
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
After many tries, I think I finally know the documentation by heart.
Then, I need your help .. I don't understand why Doctrine show me this error :
Invalid parameter number: number of bound variables does not match
number of tokens
Here is my code :
$qb = $this->em->createQueryBuilder();
$qb->select('m')
->from('Entities\Marque', 'm')
->leftJoin('m.magasin', 'ma')
->where('m.nom = :marque AND ma.nom LIKE :magasin')
->setParameter('marque', $marque)
->setParameter('magasin', '%'.$matchesNumber[1].'%');
$results = $qb->getQuery()->getArrayResult();
Thank you in advance for your answer.
This also happens if you accidentally use more than one where(), which happened to me once.
$em = $this->getEntityManager();
$query = $em->createQueryBuilder()
->from('AppBundle:SomeEntity', 's')
->select('s')
->where('s.foo = :foo')
->where('s.bar = :bar') // <- HERE
->setParameter('foo', 'Foo Value')
->setParameter('bar', 'Bar Value');
Should be:
$em = $this->getEntityManager();
$query = $em->createQueryBuilder()
->from('AppBundle:SomeEntity', 's')
->select('s')
->where('s.foo = :foo')
->andWhere('s.bar = :bar') // <- CHANGE TO andWhere()
->setParameter('foo', 'Foo Value')
->setParameter('bar', 'Bar Value');
Hope this helps someone.
I presume ->setParameter overrides the previous one.
For multiple Parameters use:
->setParameters(['key1' => $value1, 'key2' => $value2])
See Doctrine Upgrade:
From now on, parameters in queries is an ArrayCollection instead of a simple array. This >affects heavily the usage of setParameters(), because it will not append anymore parameters >to query, but will actually override the already defined ones. Whenever you are retrieving a >parameter (ie. $query->getParameter(1))
Doctrine Upgrade Description
Maybe that also applies to setParameter?
I'm so sorry .. I just found my error .. Later, like more later in my code .. I type a new query with my old "$qb" ..
I'm such a noob !
$qb = $this->em->createQueryBuilder();
$parameters = array('marque'=>$marque, 'magasin'=>'%'.$matchesNumber[1].'%');
$qb->select('m')
->from('Entities\Marque', 'm')
->leftJoin('m.magasin', 'ma')
->where('m.nom = :marque')
->andWhere('ma.nom LIKE :magasin')
->setParameters($parameters);
$results = $qb->getQuery()->getArrayResult();
I'm using Doctrine 1.2 and Symfony 1.4.
In my action, I have two different query that return different result set. Somehow the second query seem to change the result (or the reference?) of the first one and I don't have any clue why..
Here is an example:
$this->categories = Doctrine_Query::create()
->from('Categorie AS c')
->innerJoin('c.Activite AS a')
->where('a.archive = ?', false)
->execute();
print_r($this->categories->toArray()); // Return $this->categories results, normal behavior.
$this->evil_query = Doctrine_Query::create()
->from('Categorie AS c')
->innerJoin('c.Activite AS a')
->where('a.archive = ?', true)
->execute();
print_r($this->categories->toArray()); // Should be the same as before, but it return $this->evil_query results instead!
Why Doctrine behave this way ? It's totally driving me crazy. Thanks!
To make it simple it seem like the Query 2 are hijacking the Query 1 result.
Use something like this between queries ($em - entity manager):
$em->clear(); // Detaches all objects from Doctrine!
http://docs.doctrine-project.org/en/2.0.x/reference/batch-processing.html
In the API docs for the toArray() method in Doctrine_Collection it says:
Mimics the result of a $query->execute(array(), Doctrine_Core::HYDRATE_ARRAY);
I suspect to answer this question to your satisfaction you're going to have to go through the source code.
This seems like it has to be an issue of $this->categories and $this->evil_query pointing to the same place. What are the results of $this->evil_query === $this->categories and $this->evil_query == $this->categories?
Hubert, have you tried storing the query into a separate variable and then calling the execute() method on it?
I mean something like:
$good_query = Doctrine_Query::create()
->from('...')
->innerJoin('...')
->where('...', false)
;
$evil_query = Doctrine_Query::create()
->from('...')
->innerJoin('...')
->where('...', true)
;
$this->categories = $good_query->execute();
$this->evil_query = $evil_query->execute();
It seems like both attributes (categories and evil_query) are pointing at the same object.
Erm, after both queries you print_r the result of the first query - change the last line to print_r($this->evil_query->toArray()); to see the difference :)