Q:

How can I use a variable in a mysql query?

This is my function:
  public function findByIdJoinedToCategory($id)
     {
         $query = $this->getEntityManager()
             ->createQuery(
                 'SELECT a, b
                 FROM App\Entity\Products a
                 JOIN a.productgroup b
                 WHERE a.id = 2');
     }

I simply try to replace 2 with the variable $id. But I do not succeed:
  public function findByIdJoinedToCategory($id)
     {
         $query = $this->getEntityManager()
             ->createQuery(
                 'SELECT a, b
                 FROM App\Entity\Products a
                 JOIN a.productgroup b
                 WHERE a.id = $id');
     }

I get the error message:

[Syntax Error] line 0, col 125: Error: Expected Literal, got '$'

A:

In short, when placing special characters such as a new line or vars in a string you need to use double quotes.
To place a var in a string you need to concatenate it into the string as follows:
'SELECT a, b
FROM App\Entity\Products a
JOIN a.productgroup b
WHERE a.id = '.$id

You are able to able to place the var inside of the string as follows:
"SELECT a, b
FROM App\Entity\Products a
JOIN a.productgroup b
WHERE a.id = $id"

However, you may find the following more readable:
"SELECT a, b
FROM App\Entity\Products a
JOIN a.productgroup b
WHERE a.id = {$id}"

