How to print query in Symfony?

by elwin_wilderman , in category: PHP , 2 years ago

How to print query in Symfony?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@elwin_wilderman Use getSQL() method to print SQL query and getParameters() methods to print SQL parameters in Symfony, here is code as example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class ProductRepository extends EntityRepository
{
    /**
     * Get product object by slug.
     *
     * @param string $slug
     * @param string $locale
     */
    public function findProductBySlug(string $slug, string $locale)
    {
        $qb = $this->getEntityManager()->createQueryBuilder();

        $query = $qb->select('p')
            ->from(Product::class, 'p')
            ->where('p.slug = :slug')
            ->andWhere($qb->expr()->neq('p.deleted', 1))
            ->andWhere('p.locale = :locale')
            ->setParameter('slug', $slug)
            ->setParameter('locale', $locale)
            ->getQuery();

        // Print SQL query:
        echo $query->getSQL();
        // Print ALL SQL Parameters:
        echo $query->getParameters();
        // die();
        return $query->getOneOrNullResult();
    }
}
by lavina.marks , a year ago

@elwin_wilderman 

To print a query in Symfony, you can follow these steps:

  1. In your Symfony environment, open the file where the query is being executed.
  2. Use the doctrine dump function to print the SQL query and its parameters.
1
2
3
4
5
6
7
8
$query = $em->createQuery('SELECT p FROM AppEntityProduct p WHERE p.price > :price');
$query->setParameter('price', 10);

//print the query
echo $query->getSQL();
echo "
";
print_r($query->getParameters());


  1. Alternatively, you can also enable debug mode in Symfony's configuration file to display all SQL queries on the web page.
1
2
3
4
5
6
#config/packages/dev/doctrine.yaml

doctrine:
    dbal:
        #...
        logging: true


After enabling the debug mode, you can view all the SQL queries executed by visiting the profiler page in your Symfony application.