pdo get field names

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

I'm using PDO for the first time. I want to get the field/column names
from a SELECT query.  I can get the names from the associative array
returned by fetch(). But how do I get the field names if the SELECT
query returns no rows?  I could do this before with the
xxxx_fetch_field() functions.

Here's a condensed version of my code:

// query the database
$DbToQuery = new PDO("sqlite::memory:");
$DbToQuery->query("CREATE TABLE MyTable (MyField TEXT)");
$sql = "SELECT * FROM MyTable";
$result = $DbToQuery->query($sql);
// Get the number of columns
$Cols = $result->columnCount();
// Loop through the results
$countrows = 1;
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
   if($countrows == 1) {
     // Print column names
     print join(",", array_keys($row));
   // handle the row data
   // ...

Site Timeline