Selecting results as a comma-separated string
Using one of the below queries removes the need to iterate over the result sets to construct the CSV strings. When a single result is expected, a -&gt;fetch() instead of -&gt;fetchAll() would do.

Conclusion: implode goes away, while and for loops go away the only iteration needed would be in case of multiple CSV result sets.

SELECT GROUP_CONCAT(columnName) FROM Table1; # for single column

SELECT CONCAT(columnA,",",columnB) from Table2; # for multi cols


You might have issues creating prepared statements for this; I don't know.

example for the first query:

&lt;?php

$conn = new PDO("mysql:host=localhost;dbname=test", "root", "");

$stmt = $conn-&gt;query("SELECT GROUP_CONCAT(columnName) FROM Table1");

$result = $stmt-&gt;fetch(PDO::FETCH_ASSOC);

var_dump($result);