2

I'm sure this exists, but after a few dozen searches, I'm not any closer to an answer.

After I've executed a query in Drupal (for example)

$dbParts = db_select("parts", "p")
    ->fields("p")
    ->execute();

How can I get a count (or list) of fields without pulling this first record? With MySQL I was able to use "mysql_num_fields".

UPDATE

Just to give a little background... I have some old code (using mysql_* functions) that export data to the DBF format. In order to format the header of the DBF, I need to have a field count (and information about the fields) even if the record count is 0 in order to format a "blank" database.

2

Drupal uses PDO, whose equivalent function is PDOStatement::columnCount():

Returns the number of columns in the result set represented by the PDOStatement object. If there is no result set, PDOStatement::columnCount() returns 0.

So what you're looking for isn't totally possible these days. I can't see a Drupal equivalent of columnCount(), but you can always grab the PDO connection object with Database::getConnection(), and work with that directly if it'll help you get part of the way there.

To take a different approach, and assuming you've used the schema API to describe your table to Drupal, you can query that instead:

$table = drupal_get_schema_unprocessed('MYMODULE', 'table_name');
$fields = $table['fields'];
|improve this answer|||||
  • I just tried $dbParts->columnCount() and it actually works. So I guess the Drupal object is some sort of extension of the 'PDOStatement' object (making it's built in functions available). Thanks! =) – DragonYen Jun 2 '14 at 20:19
  • Sweet, didn't know that! – Clive Jun 2 '14 at 20:37
  • Didn't know that?? api.drupal.org/api/drupal/includes!database!database.inc/class/… class DatabaseStatementBase extends \PDOStatement implements DatabaseStatementInterface – user49 Jun 4 '14 at 8:55
  • @chx Just never looked, thinking about it I've used PDO methods on a SelectQuery before so on some level I guess I knew ;) – Clive Jun 4 '14 at 8:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.