2

I'm creating a query like this

    $om = $this->getContainer()->get('doctrine')->getManager();

    $qb = $om->createQueryBuilder()
            ->from('ProbusQuoteExtraBundle:Quote', 'q')
            ->select('q', 'b')
            ->join('q.booking', 'b')
            ->orderBy('q.id', 'asc')
            ->where("q.startDate >= '" . date('Y-m-d H:i:s', strtotime('-1 hour')) . "'")
            ->andWhere("q.startDate <= '" . date('Y-m-d H:i:s', time()) . "'")
    ;

i want to check if i created correct query or not by using this

echo $qb->getQuery();

but it gives error.

4
  • 3
    "but it gives error" so please display that error... Commented May 21, 2015 at 10:04
  • 3
    Maybe because you are trying to use Query object as a string, because getQuery() method will return object. Try with getDQL() or use var_dump instead echo. Commented May 21, 2015 at 10:13
  • 2
    echo $qb->getQuery()->getSQL(); might help. Also, remember the debugging toolbar in your development environment shows all the queries that have run. Commented May 21, 2015 at 10:24
  • thanks all for your time and help Commented May 21, 2015 at 11:19

1 Answer 1

3

If you want to check your statement in DQL or SQL you can do this by calling ->getSQL(), or ->getDQL() on $qb->getQuery();

Also I recommend installing xdebug and using var_dump():

$sql = $qb->getQuery()->getSQL();
$dql = $qb->getQuery()->getDQL();
var_dump($sql);
var_dump($dql);

It will print both, a SQL and DQL dump of your QueryBuilder

And since we're at it, instead of injecting your parameters by concatenation use the QueryBuilders ->setParameters() method:

->where("q.startDate >= :startDate")
->andWhere("q.startDate <= :endDate")
->setParameters(array(
         'startDate' => date('Y-m-d H:i:s', strtotime('-1 hour')), 
         'endDate' => date('Y-m-d H:i:s', time()),
))

You can find more on that in the Doctrine2 documentation.

Sign up to request clarification or add additional context in comments.

4 Comments

thanks. it worked. one more question, how can i read and display result after query is executed? $result = $qb->getQuery()->getResult(); print_r($result);
this is exactly how. This is your mapped result.
its giving error object of class datetime could not be converted to string
that means your result is, or contains a datetime object. Install xdebug, and use var_dump to see what you get. A possibility for a string representation of a DateTime Object ist ->format('Y-m-d H:i:s'). Check the documentation php.net/manual/de/class.datetime.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.