title: Doctrine and Symfony2: How to execute raw queries (General error: 2014 Cannot execute queries while > other unbuffered queries are active)
body: <p>I'm trying to execute a raw query using Doctrine into the Symfony framework.</p>
  
  <p>Here there is the code:</p>
  
  <pre><code>class MessagesHandler
  {
      /** @var \Doctrine\Common\Persistence\ObjectManager The entity manager used to access entities */
      protected $em = null;
  
      public function __construct($em)
      {
          $this-&gt;em = $em;
      }
  
      public function getMessagesToPost($user)
      {
          $query = 'SELECT COUNT(*) FROM `messages` WHERE `posted_by` = ' . $user-&gt;getId() . ' AND `message_posted` = 0';
  
          return $this-&gt;em-&gt;getConnection()-&gt;exec($query);
      }
  </code></pre>
  
  <p>I have set the class MessagesHandler as a service:</p>
  
  <pre><code>services:
      shq.handler.Messages:
                  class: AppBundle\Handler\MessagesHandler
                  arguments: ["@doctrine.orm.entity_manager"]
  </code></pre>
  
  <p>Now, when I execute the code, I receive the following error:</p>
  
  <blockquote>
    <p>SQLSTATE[HY000]: General error: 2014 Cannot execute queries while
    other unbuffered queries are active. Consider using
    PDOStatement::fetchAll(). Alternatively, if your code is only ever
    going to run against mysql, you may enable query buffering by setting
    the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.")...</p>
  </blockquote>
  
  <p><strong>How can I use <code>PDOStatement::fetchAll()</code>?</strong></p>