Prepared statement with variables in PHP / Laravel - Cannot execute queries while other unbuffered queries are active
<p>I have the following query (the query is for experimental use).</p>

<pre><code>SELECT @sql:=GROUP_CONCAT(DISTINCT CONCAT( 'MAX(case when alias = ''', alias, ''' then data_varchar end) AS ', alias )) from documents 
left join property_values ON property_values.document_id=documents.id 
left join properties on properties.id = property_values.property_id;

SET @sql = CONCAT('SELECT ', @sql, ', documents.* from documents left join property_values on property_values.document_id=documents.id left join properties on properties.id = property_values.property_id GROUP BY documents.id');

PREPARE stmt FROM @sql;

EXECUTE stmt;

DEALLOCATE PREPARE stmt; 
</code></pre>

<p>I just can't get it to work with PHP / Laravel. I am not sure what to put inside a prepared statement and when to execute what. Tried many thing but most of the time I'm getting the error:</p>

<p><strong>Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll()</strong></p>

<p>My code:</p>

<pre><code>DB::select(DB::raw('SELECT @sql:=GROUP_CONCAT(DISTINCT CONCAT( \'MAX(case when alias = \'\'\', alias, \'\'\' then data_varchar end) AS \', alias )) from documents 
                        left join property_values ON property_values.document_id=documents.id 
                        left join properties on properties.id = property_values.property_id;'));

DB::select(DB::raw('SET @sql = CONCAT(\'SELECT \', @sql, \', documents.* from documents left join property_values on property_values.document_id=documents.id left join properties on properties.id = property_values.property_id GROUP BY documents.id\');'));


DB::raw('PREPARE stmt FROM @sql;');

$result = DB::select(DB::raw('EXECUTE stmt'));
</code></pre>

<p>The first 2 queries seem to executed just fine. But on prepare it crashes.</p>

<p><a href="https://i.stack.imgur.com/oLTJF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oLTJF.png" alt="enter image description here"></a></p>